0

I’m attempting to capture output from a long running SSH command that may take a few seconds to initially produce any text output once called and may take up to a minute to fully complete.

The below code snippet works fine if I issue a simple command to execute such as ls that produces immediate output into the output stream.

However, I get nothing returned and SSH disconnects if I run a command that doesn’t instantly produce any output.

using (var sshClient = new SshClient(target, 22, userName, password))
{
    sshClient.Connect();
    var cmd = sshClient.CreateCommand(command);
    var result = cmd.BeginExecute();

    using (var reader = new StreamReader(cmd.OutputStream))
    {
        while (!reader.EndOfStream || !result.IsCompleted)
        {
            string line = reader.ReadLine();
            if (line != null)
            {
                Console.WriteLine(line);
            }
        }
        sshClient.Disconnect();
    }
}
0

1 Answer 1

1

BeginExecute begins an asynchronous command execution. You need to wait and keep reading the output stream until it completes.

In a simple way,

        using (var sshClient = new SshClient(host, 22, username, password)) {
            sshClient.Connect();
            var cmd = sshClient.CreateCommand("for i in `seq 1 10`; do sleep 1; echo $i; done");
            var asyncResult = cmd.BeginExecute();
            var outputReader = new StreamReader(cmd.OutputStream);
            string output;
            while (!asyncResult.IsCompleted) {
                output = outputReader.ReadToEnd();
                Console.Out.Write(output);
            }
            output = outputReader.ReadToEnd();
            Console.Out.Write(output);
        }
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, I'm getting the expected results now.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.