Reputation: 3
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();
}
}
Upvotes: 0
Views: 1106
Reputation: 1096
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);
}
Upvotes: 1