Run Unix commands using PuTTY in C# [duplicate]

天涯浪子 提交于 2019-12-07 20:36:57

问题


I am trying to run Unix commands in PuTTY using C#. I have the below code. But the code is not working. I am not able to open PuTTY.

static void Main(string[] args)
{
    Process cmd = new Process();
    cmd.StartInfo.FileName = @"C:\Windows\System32\cmd";
    cmd.StartInfo.UseShellExecute = false;
    cmd.StartInfo.RedirectStandardInput = false;
    cmd.StartInfo.RedirectStandardOutput = true;
    cmd.Start();
    cmd.StartInfo.Arguments = "C:\Users\win7\Desktop\putty.exe -ssh mahi@192.168.37.129 22 -pw mahi";
}

回答1:


  • The putty.exe is a GUI application. It's intended to interactive use, not for automation. There's no point trying to redirect its standard output, as it's not using it.

  • For automation, use another tool from PuTTY package, the plink.exe.
    It's a console application, so you can redirect its standard output/input.

  • There's no point trying to execute an application indirectly via the cmd.exe. Execute it directly.

  • You need to redirect standard input too, to be able to feed commands to the Plink.

  • You have to provide arguments before calling the .Start().

  • You may want to redirect error output too (the RedirectStandardError). Though note that you will need to read output and error output in parallel, what complicates the code.


static void Main(string[] args)
{
    Process cmd = new Process();
    cmd.StartInfo.FileName = @"C:\Program Files (x86)\PuTTY\plink.exe";
    cmd.StartInfo.UseShellExecute = false;
    cmd.StartInfo.RedirectStandardInput = true;
    cmd.StartInfo.RedirectStandardOutput = true;
    cmd.StartInfo.Arguments = "-ssh mahi@192.168.37.129 22 -pw mahi";
    cmd.Start();
    cmd.StandardInput.WriteLine("./myscript.sh");
    cmd.StandardInput.WriteLine("exit");
    string output = cmd.StandardOutput.ReadToEnd();
}



回答2:


This should work:

    static void Main(string[] args)
    {
        ProcessStartInfo cmd = new ProcessStartInfo();
        cmd.FileName = @"C:\Users\win7\Desktop\putty.exe";
        cmd.UseShellExecute = false;
        cmd.RedirectStandardInput = false;
        cmd.RedirectStandardOutput = true;
        cmd.Arguments = "-ssh mahi@192.168.37.129 22 -pw mahi";
        using (Process process = Process.Start(cmd))
        {
            process.WaitForExit();
        }
    }


来源:https://stackoverflow.com/questions/27592329/run-unix-commands-using-putty-in-c-sharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!