Run and execute multiple dependent SSH commands using C#

筅森魡賤 提交于 2020-06-13 07:02:18

问题


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.


回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/56434268/run-and-execute-multiple-dependent-ssh-commands-using-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!