2013. 12. 10. 06:54

Run a sudo command using RunCommand

I had googled for this and got the useful information:



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.



Here is alternative to run a command


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


Source: https://sshnet.codeplex.com/discussions/269667


If sudo command doesn't prompt password, output will be like the following:


administrator@ubuntu:~$ echo "test" | sudo -S ls
[sudo] password for administrator: Sorry, try again.
[sudo] password for administrator:
Sorry, try again.
[sudo] password for administrator:
Sorry, try again.
sudo: 3 incorrect password attempts


If you use RunCommand, it will be ok because there is no connection (or context) between each RunCommand. I mean that sudo command using RunCommand will prompt password all the time.


Here is Sample codes.


using (SshClient client = new SshClient(connectionInfo)) { client.Connect(); using (var cmd = client.CreateCommand("echo \"password\" | sudo -S ls")) { cmd.CommandTimeout = TimeSpan.FromSeconds(10); var asynch = cmd.BeginExecute(); var reader = new StreamReader(cmd.OutputStream); while (!asynch.IsCompleted) { var result = reader.ReadToEnd(); if (string.IsNullOrEmpty(result)) continue; Console.Write(result); } cmd.EndExecute(asynch); client.Disconnect(); } }