Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

.net - Execute multiple dependent SSH commands using SSH.NET in C#

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...