首页 > 解决方案 > Renci.SshNet SshStream.Flush() 不工作

问题描述

我收到一个异常错误,因为当我读取 ShellStream 上的最后一个命令时,即使我使用 ShellStream.Flush() 刷新了 Stream,我也会得到一些旧输出。

所有这些都是 foreach 循环的一部分:

            //Type ls | wc command
            ssh_Shell_Stream.WriteLine(cmd_Ls_Wc);
            Thread.Sleep(1000); // Prevents the shell from losing the output if it becomes too slow

            string stream = "";
            string[] stream_Last_Cmd_Arr;
            string stream_Last_Cmd;
            string line1;

            // Read with a suitable timeout to avoid hanging
            while ((line1 = ssh_Shell_Stream.ReadLine(TimeSpan.FromSeconds(2))) != null)
            {
                // Assign the entire command stream to stream string
                stream = stream + line1 + "\n";
                Thread.Sleep(1000);
            }
            // Retrieve only last command output
            stream_Last_Cmd_Arr = stream.Split('\n');           
            stream_Last_Cmd = stream_Last_Cmd_Arr[stream_Last_Cmd_Arr.Length-2];

            // Converting to int to later determine if there's more than one folder
            int ls_wc_result = Convert.ToInt32(stream_Last_Cmd);

Convert.ToInt32(stream_Last_Cmd);几个循环之后,我收到一个异常错误,因为最后一个命令与我实际需要的“ls | wc -l”不一致。这就像我让流缓冲区卡在“ls | wc -l”命令之前抛出的“curl”命令上。

我的流继续看起来像这样:"bash$ tail -10000 /xxxx/xxx/xxx/xxx/xxx.log > /tmp/xx\xx.root.log\ncurl -T /xx/xxx.x.log ftp://10.10.10.1:21 --user xxx-xxx:xxxx\nbash$ curl -T /xx/xxx.xx.log ftp://1.1.1.1 --user xxxx\xxx-xxxx:xxxxxx\n % Total % Received % Xferd Average Speed Time Time Time Current\n Dload Upload Total Spent Left Speed\n\r 0 0 0 0 0 0 0 0 --:--:-- --:--:-- --:--:-- 0\r100 1447k 0 0 100 1447k 0 36.2M --:--:-- --:--:-- --:--:-- 37.2M\n"

虽然,站在我抛出的命令,它应该是这样的:"bash$ ls /xxx/xx/xx/ | wc -l\n1\n"

无论如何,我确定在继续执行其他命令之前,我已经暂停了主线程足够的时间。

除此之外,也许 Flush() 方法没有正确清理流缓冲区?

标签: c#ssh

解决方案


看来这可能是一个已知的错误:

我决定使用 Dispose() 方法删除整个 shell 并在每次迭代时创建一个新的 shell 作为解决方法:

foreach (string SerialNumber in file_Lines)
                {
                    //Creating our ShellStream
                    var ssh_Shell_Stream = CreateShellStream("checker_Terminal", 80, 80, 1024, 1024, 1024);
                    // Send the command
                    ssh_Shell_Stream.WriteLine(cmd1);

                    //Wait 2 seconds and the type the password
                    Thread.Sleep(2000);
                    ssh_Shell_Stream.WriteLine(cmd2);

                    Thread.Sleep(250);
                    SSH_Class.Extractor(X, Y, ssh_Shell_Stream);
                    Thread.Sleep(250);

                    ssh_Shell_Stream.Dispose();
                }

推荐阅读