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
230 views
in Technique[技术] by (71.8m points)

c# - SSH.NET is not executing command on device

I'm trying to send a simple command over SSH using SSH.NET. Even the simplest test code fails. Here is a snippet.

using (var ssh = new SshClient("ip", port, "username", "password"))
{
    ssh.Connect();
    while (true)
    {
        var result = ssh.RunCommand("AT").Execute(); 
        Console.Out.WriteLine(result);
    }
}

The AT command should echo back OK but doesn't. Instead I receive a custom timeout message issued by the SSH target. I see the device name in the timeout message which corresponds to the prompt it uses and from that i can conclude that the login works (also tested with various SSH programs) but the command itself is not executed. I tried adding and to the commands but to no results. What am I doing wrong?

Edit 1: output from result is Command Line Interface DeviceName> Custom idle timeout I think the line endings are converted to Windows ones by Visual Studio.

Edit 2: Using Plink plink.exe username@ip -pw password "AT" > log.txt results in the same output as Visual Studio. Plink waits till timeout and terminates and log.txtcontains Command Line Interface DeviceName> Custom idle timeout.

Using PuTTY I see that

Using username "username".
username@host's password:

Entering character mode
Escape character is '^]'.

Command Line Interface
DeviceName> 

is written before you can start entering commands. Might it be that the command is entered before the host is ready to receive it and as a result the command hangs until some reaction comes?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Your server obviously does not support the SSH "exec" channel that is used behind the SSH.NET SshClient.RunCommand method and PLink's plink.exe command syntax.

Or actually it does support it, but incorrectly. It seems to start an interactive session (a shell), instead of executing the command.

To confirm this assumption, try this with PLink:

echo AT| plink username@ip -pw password > log.txt

If that works, you may need to use the SshClient.CreateShell (SSH "shell" channel") instead of the SshClient.RunCommand. While this is generally a wrong approach, you need to take this approach due to your broken server.


A similar question for Python/Paramiko:
Executing command using Paramiko exec_command on device is not working
.


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

1.4m articles

1.4m replys

5 comments

57.0k users

...