1

I want to change directory inside SSH using C# with SSH.NET library:

SshClient cSSH = new SshClient("192.168.80.21", 22, "appmi", "Appmi");

cSSH.Connect();

Console.WriteLine("current directory:");
Console.WriteLine(cSSH.CreateCommand("pwd").Execute());

Console.WriteLine("change directory");
Console.WriteLine(cSSH.CreateCommand("cdr abc-log").Execute());

Console.WriteLine("show directory");
Console.WriteLine(cSSH.CreateCommand("pwd").Execute());

cSSH.Disconnect();
cSSH.Dispose();

Console.ReadKey();

But it's not working. I have also checked below:

Console.WriteLine(cSSH.RunCommand("cdr abc-log").Execute());

but still is not working.

Martin Prikryl
  • 188,800
  • 56
  • 490
  • 992
4est
  • 3,010
  • 6
  • 41
  • 63

2 Answers2

4

I believe you want the commands to affect the subsequent commands.

But SshClient.CreateCommand uses SSH "exec" channel to execute the command. That means that every command is executed in an isolated shell and has no effect on the other commands.


If you need to execute commands in a way that previous commands affect later commands (like changing a working directory or setting an environment variable), you have to execute all commands in the same channel. Use an appropriate construct of the server's shell for that. On most systems you can use semicolons:

Console.WriteLine(cSSH.CreateCommand("pwd ; cdr abc-log ; pwd").Execute());

On *nix servers, you can also use && to make the following commands be executed only when the previous commands succeeded:

Console.WriteLine(cSSH.CreateCommand("pwd && cdr abc-log && pwd").Execute());

Some less common systems (for example AIX) may not even have a way to execute multiple commands in one "command-line". In these cases, you may need to use a shell channel, what is otherwise not recommended.

Also when the other commands are actually sub commands of the first command, you may need different solution.

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

Martin Prikryl
  • 188,800
  • 56
  • 490
  • 992
0

this is what I have done and its working for me:

SshClient sshClient = new SshClient("some IP", 22, "loign", "pwd");
sshClient.Connect();

ShellStream shellStream = sshClient.CreateShellStream("xterm", 80, 40, 80, 40, 1024);

string cmd = "ls";
shellStream.WriteLine(cmd + "; echo !");
while (shellStream.Length == 0)
 Thread.Sleep(500);

StringBuilder result = new StringBuilder();
string line;

string dbt = @"PuttyTest.txt";
StreamWriter sw = new StreamWriter(dbt, append: true);           

 while ((line = shellStream.ReadLine()) != "!")
 {
  result.AppendLine(line);
  sw.WriteLine(line);
 }            

 sw.Close();
 sshClient.Disconnect();
 sshClient.Dispose();
 Console.ReadKey();
4est
  • 3,010
  • 6
  • 41
  • 63
  • 1
    Using the *shell* channel is not recommended for command automation. The shell channel is intended for implementing an interactive SSH client. – Martin Prikryl Jan 31 '20 at 06:44