远程Linux机器上有一个运行时间很长的脚本script.sh。我需要启动它并实时监视它的事件。事件期间的脚本可能会输出为stdoutstderr。我正在寻找一种捕获两个流的方法。

我使用Renci SSH.NET上载script.sh并启动它,因此,很高兴看到绑定(bind)到该库的解决方案。在我看来,完美的解决方案是新方法:

var realTimeScreen= ...;

var commandExecutionStatus = sshClient.RunCommandAsync(
    command: './script.sh',
    stdoutEventHandler: stdoutString => realTimeScreen.UpdateStdout(stdString)
    stderrEventHandler: stderrString => realTimeScreen.UpdateStderr(stderrString));
...
commandExecutionStatus.ContinueWith(monitoringTask =>
{
    if (monitoringTask.Completed)
    {
        realTimeScreen.Finish();
    }
});

最佳答案

使用SshClient.CreateCommand方法。它返回SshCommand实例。SshCommand类具有ExtendedOutputStream属性,该属性返回具有stdout和stderr的流。
参见SshCommandTest.cs:

public void Test_Execute_ExtendedOutputStream()
{
    var host = Resources.HOST;
    var username = Resources.USERNAME;
    var password = Resources.PASSWORD;

    using (var client = new SshClient(host, username, password))
    {
        #region Example SshCommand CreateCommand Execute ExtendedOutputStream

        client.Connect();
        var cmd = client.CreateCommand("echo 12345; echo 654321 >&2");
        var result = cmd.Execute();

        Console.Write(result);

        var reader = new StreamReader(cmd.ExtendedOutputStream);
        Console.WriteLine("DEBUG:");
        Console.Write(reader.ReadToEnd());

        client.Disconnect();

        #endregion

        Assert.Inconclusive();
    }
}

另请参见完整的代码,以了解类似WinForms的问题Execute long time command in SSH.NET and display the results continuously in TextBox

10-08 14:18