su or sudo root

Aug 19, 2011 at 8:58 AM

 var connectionInfo = new PasswordConnectionInfo("", "user", "pass");
            using (var client = new SshClient(connectionInfo))
                textBox1.Text += client.RunCommand("whoami").Execute();
                textBox1.Text += client.RunCommand("su root").Execute();
                textBox1.Text += client.RunCommand("whoami").Execute();


I don't know how to send the password. If I use for the second command sudo, the app hangs. I cannot log in directly with root. All I need is to get the output of the tcpdump command, that I have to run with root. Any suggestion?

Aug 19, 2011 at 1:14 PM

Unfortunalty, when yo execute a command using RunCommand you cannot run it using su or sudo.

The reason is that command executes as one single unit and have no knowledge or previous commands or shell it executes in.

It seems that SSH Server creates context for command execution, executes it and the deletes this context.

One thing you can try to execute the command is shell object, this way it creates shell, pretty much like you do with putty, and lets you send text and get text back, which you can analyze later.


Hope it helps,



Aug 22, 2011 at 7:55 AM

I am trying to run:


var connectionInfo = new PasswordConnectionInfo("", "testuser", "testuserpassword");
            using (var ssh = new SshClient(connectionInfo))
                var input = new MemoryStream(Encoding.ASCII.GetBytes("su root\r\ntestpass\r\n")); //"testpass" is the password
                var output = Console.OpenStandardOutput();
                var shell = ssh.CreateShell(input, output,output, "xterm", 80, 24, 800, 600, "");
                shell.Stopped += delegate {

The output is: Last login: Mon Aug 22 10:39:29 2011 from

su root


-bash-3.2$ su root
A first chance exception of type 'System.Net.Sockets.SocketException' occurred in System.dll
A first chance exception of type 'System.Net.Sockets.SocketException' occurred in Renci.SshNet.dll

It can't send the password to the shell. Is this the right way? If I want to send more commands to shell, I have to separate them with \r\n?


Aug 27, 2011 at 11:59 PM
Edited Aug 28, 2011 at 12:01 AM

You actually may run sudo using RunCommand as follows:

client.RunCommand("echo \"userpwd\" | sudo -S command").Execute()

-S key tells sudo to take password from stdin, which is piped from the previous echo command

Apr 14, 2015 at 1:21 AM
Hi tried above logic "client.RunCommand("echo \"userpwd\" | sudo -S command").Execute()"

but in our case we don't know the password for security reasons, and we use secured key to login.

so is there any workaround for that ?