SSH.NET RunCommand将命令输出保存到文件

时间:2013-12-04 15:10:19

标签: c# ssh stdout ssh.net runcommand

我正在尝试通过SSH在远程服务器上运行命令。

我需要运行的命令的输出保存在该远程服务器上的文件中。

我一直在尝试以下方式

// ssh is the SshClient which is already set up
ssh.Connect();
ssh.RunCommand("echo 1 > C:\test.csv"); //Doesn't create a file
ssh.Disconnect();

为什么这不适用于SSH.NET?如果我使用相同的凭证通过putty运行它,它完全正常。

编辑(工作守则):

我做了更多的游戏并发现了以下工作:

// ssh is the SshClient which is already set up
ssh.Connect();
var shell = ssh.CreateShellStream("cmd.exe", 80, 24, 800, 600, 1024);
var reader = new StreamReader(shell);
var writer = new StreamWriter(shell);
writer.AutoFlush = true;

while (!shell.DataAvailable)
    System.Threading.Thread.Sleep(1000); //This wait period seems required

writer.WriteLine("echo 1 > C:\test.csv");

while (!shell.DataAvailable)
    System.Threading.Thread.Sleep(1000); //This wait period seems required

ssh.Disconnect();

虽然有效,但我仍然不明白这里到底发生了什么。有人可以解释一下吗?

1 个答案:

答案 0 :(得分:2)

试试这个功能: 只需将结果保存到变量或使用StreamWriter

写入结果
private void writeMe()
{
    using (StreamWriter sw = new StreamWriter(filename)
    {
        string result = eSshCom(command);
        sw.WriteLine(result);
    } 
} 



private string eSshCom(string getCommand)
            {
            this.res = "";

            var connectionInfo = new KeyboardInteractiveConnectionInfo(ipaddress, 22, username);

            connectionInfo.AuthenticationPrompt += delegate(object asender, AuthenticationPromptEventArgs xe)
            {
                foreach (var prompt in xe.Prompts)
                    {
                    if (prompt.Request.Equals("Password: ", StringComparison.InvariantCultureIgnoreCase))
                        {
                        prompt.Response = password;
                        }
                    }
            };

            using (var ssh = new SshClient(connectionInfo))
                {
                    ssh.Connect();
                    var cmd = ssh.RunCommand(getCommand);
                    this.res = cmd.Result;
                    ssh.Disconnect();

                }
            return this.res;
            }