2

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";
}
Martin Prikryl
  • 188,800
  • 56
  • 490
  • 992
user2684816
  • 31
  • 1
  • 1
  • 5
  • You've gone a bit wrong there mate. Have a look at http://stackoverflow.com/questions/6147203/automating-running-command-on-linux-from-windows-using-putty – Tony Hopkinson Dec 21 '14 at 18:28

2 Answers2

8

First, in general, you better use native .NET SSH library, like SSH.NET, instead of running external application.

See How to run commands on SSH server in C#?


  • 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();
}
Martin Prikryl
  • 188,800
  • 56
  • 490
  • 992
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();
        }
    }
Grady G Cooper
  • 1,044
  • 8
  • 19