I am working on a Windows app with C# as a programming langugage.
Requirement is
Putty has the command line option -m {script_file} which allows you to specify a script file to be run against the remote server. After all the commands are run, putty will exit.
You could save the command to be run in a script file, call Putty, and delete the script file when you're done.
The following code works for me:
string hostname = "hostname";
string login = "login";
string password = "password";
string command = "rm ~/dir1/dir2/NewFolder/*.txt"; // modify this to suit your needs
const string scriptFileName = @"remote_commands.sh";
File.WriteAllText(scriptFileName, command);
var startInfo = new ProcessStartInfo();
startInfo.FileName = @"C:\Putty\putty.exe";
startInfo.Arguments = string.Format("{0}@{1} -pw {2} -m {3}",
login, hostname, password, scriptFileName);
var process = new Process {StartInfo = startInfo};
process.Start();
process.WaitForExit();
File.Delete(scriptFileName);
If all you want to do is send a single command to the server, this solution will do. If you need more advanced functionality, like reading the server response, you should check out Thomas' answer.
Here's how to use plink to run commands and get their output:
string hostname = "hostname";
string login = "login";
string password = "password";
var startInfo = new ProcessStartInfo();
startInfo.FileName = @"C:\Putty\plink.exe";
startInfo.RedirectStandardInput = true;
startInfo.RedirectStandardOutput = true;
startInfo.UseShellExecute = false;
startInfo.Arguments = string.Format("{0}@{1} -pw {2}",
login, hostname, password);
using (var process = new Process {StartInfo = startInfo})
{
process.Start();
process.StandardInput.WriteLine("ls");
process.StandardInput.WriteLine("echo 'run more commands here...'");
process.StandardInput.WriteLine("exit"); // make sure we exit at the end
string output = process.StandardOutput.ReadToEnd();
Console.WriteLine(output);
}