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();
}