Providing subcommands to a command (sudo/su) executed with SSH.NET SshClient.CreateShellStream

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.

Leave a Comment