Providing subcommands to a command (sudo/su) executed with SSH.NET SshClient.CreateShellStream
I am trying to use Renci SSH.NET to connect to a remote Linux server from a C# web application and execute shell scripts. I want to run the scripts one after another. But not getting how to run the scripts and read the output and store it in a label. I have tried the below code, but not able to pass multiple commands one line after another.
SshClient sshclient = new SshClient("host", UserName, Password);
sshclient.Connect();
ShellStream stream = sshclient.CreateShellStream("commands", 80, 24, 800, 600, 1024);
public StringBuilder sendCommand(string customCMD)
{
StringBuilder answer;
var reader = new StreamReader(stream);
var writer = new StreamWriter(stream);
writer.AutoFlush = true;
WriteStream(customCMD, writer, stream);
answer = ReadStream(reader);
return answer;
}
private void WriteStream(string cmd, StreamWriter writer, ShellStream stream)
{
writer.WriteLine(cmd);
while (stream.Length == 0)
{
Thread.Sleep(500);
}
}
private StringBuilder ReadStream(StreamReader reader)
{
StringBuilder result = new StringBuilder();
string line;
while ((line = reader.ReadLine()) != null)
{
result.AppendLine(line);
}
return result;
}
I am trying to run the below commands
sudo su - wwabc11
whoami
cd /wwabc11/batch/bin/
pwd
How to run the commands one after another and read the output information? Thanks.
Just write the "commands" to the StreamWriter
.
writer.WriteLine("sudo su - wwabc11");
writer.WriteLine("whoami");
// etc
See also C# send Ctrl+Y over SSH.NET.
Though note that using CreateShellStream
("shell" channel) is not the correct way to automate a commands execution. You should use CreateCommand
/RunCommand
("exec" channel). Though SSH.NET limited API to the "exec" channel does not support providing an input to commands executed this way. And whoami
and the others are actually inputs to sudo
/su
command.
A solution would be to provide the commands to su
on its command-line, like:
sudo su - wwabc11 -c "whoami ; cd /wwabc11/batch/bin/ ; pwd"
For an example of code that uses CreateCommand
to execute a command and reads its output, see see SSH.NET real-time command output monitoring.