Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
1.3k views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...