Execute SSH Commands in PLink using C#

Posted Thursday, January 19, 2012 in Old JamesCMS Posts

Here's a method for executing a single ssh command using plink. A timeout for reading the output is included as well. Some adjustments may need to be made to work with expected response times but the general idea is all here.

{{C#}}
private static string ExPlinkCommand(string ip, string sshuser, 
	string sshpw, string command)
{
	string param = “-l “ + sshuser + 
		“ -pw “ + sshpw + “-ssh “ + 
		sshuser + “@” + ip + “ “ + command;
	string plink = “physicalpath\plink”;
	ProcessStartInfo program = 
		new ProcessStartInfo(plink, param);
 
	program.UseShellExecute = false;
	program.RedirectStandardoutput = true;
	program.RedirectStandardInput = true;
	program.RedirectStandardError = true;
	program.CreateNoWindow = true;
 
	Process process = Process.Start(program);
	
	StringBuilder readout = new StringBuilder();
	StreamReader reader = process.StandardOutput;
	StreamReader exreader = porcess.StandardError;
	StreamWriter writer = process.StandardInput;
	writer.AutoFlush = true;
	Thread.Sleep(1000);
	writer.WriteLine(“y”);
 
	Stopwatch sw = new Stopwatch();
    sw.Start();
 
    while ((reader.Peek() >= 0 || 
			!process.HasExited) && 
    		sw.Elapsed < new TimeSpan(0,0,15))
    {
	    readout.Append(reader.ReadLine() + “\r\n”);
    }
    sw.Reset();
    while ((exreader.Peek() >= 0 || 
    		!process.HasExited) && 
    		sw.elapsed < new TimeSpan(0,0,15))
    {
	    readout.Append(exreader.ReadLine() + “\r\n”);
    }
    sw.Stop();
 
    string output = readout.ToString();
 
    if (output.StartsWith(“FATAL ERROR:”))
    {
	    throw new Exception(output);
    }
    return output;
}