简体   繁体   中英

NOT getting the full output from ssh.net SshCommand

I am using the Renci.SshNet nuget pacget (version 2020.0.1) in visual studio 2019.
What I am trying to do is to execute a command over SSH and return the whole result text.

this method works. but I am not getting the full-text result back.

/// <summary>
    /// Connects to a remote device via SSH and sends it a single command
    /// </summary>
    /// <param name="hostIp">Ip address or hostname for the targer device</param>
    /// <param name="command">A string formated command</param>
    /// <param name="username">username for target remote device login</param>
    /// <param name="password">password for target remote device login</param>
    /// <returns>Text responce from the given command</returns>
    public string SendCommand(string hostIp, string command, string username, string password)
    {
        try
        {
            // Create a SSH client object
            SshClient client = new SshClient(hostIp, PortNumber, username, password);

            #region connect to remote device

            client.Connect();

            // Shecks if there is a valid connection 
            if (client.IsConnected == false) { return string.Empty; }

            #endregion

            // Send and execute a given command on the target remote device
            SshCommand sshCommand = client.RunCommand(command);

            var test = sshCommand.OutputStream;

            string result = sshCommand.Result;

            #region close and dispose the connection

            client.Disconnect();
            client.Dispose();

            #endregion

            return result;
        }
        catch (SocketException socket)
        {
            // Debug and log a socket error
            Debug.WriteLine($"SocketException: {socket}");
            throw;
        }

If I eg. send this as the command

command = "\r\r";

I will get nothing on the console.
but if I send the same command to the client over ssh in my linux or windows terminal I will get this.

RMC3>

This indicates to me that the client device made a carriage return. (as it should).
But why can't I see this in the result string

string result = sshCommand.Result;

inside of the method?

Okay. As @MartinPrikryl pointed out in the comments above.

The SshCommand() method does not access the shell. (it uses the "exec" channel in the SSH.NET API).

If you want to access the "shell" using SSH.NET, then you will need to use the "ShellStream".

here is a link to 27 different examples of how others have used ShellStream in the real world. https://csharp.hotexamples.com/examples/Renci.SshNet/ShellStream/-/php-shellstream-class-examples.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM