'SSH.NET'에 해당되는 글 2건

  1. 2014.06.02 Linux SSH Session Timeout Setting
  2. 2013.12.10 Run a sudo command using RunCommand
2014. 6. 2. 06:42

Linux SSH Session Timeout Setting

Our project faced a very weird problem that SSH.Net cannot get the exit event after 10 minutes. Though the command was finished, SSH.Net was waiting for its completion.


The reason was caused by the time-out of the ssh session. To increase this, set it as below.


sudo vi /etc/ssh/sshd_config


# 300 secons

ClientAliveInterval 300

# 300 * (12) MAX 1 HOUR

ClientAliveCountMax 12


$ sudo service ssh restart


After this, it worked well.

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(); } }