This question already has answers here:
Automating running command on Linux from Windows using PuTTY
(9个答案)
4年前关闭。
我正在尝试使用C#在PuTTY中运行Unix命令。我有下面的代码。但是代码不起作用。我无法打开腻子。
(9个答案)
4年前关闭。
我正在尝试使用C#在PuTTY中运行Unix命令。我有下面的代码。但是代码不起作用。我无法打开腻子。
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";
}
最佳答案
putty.exe
是一个GUI应用程序。它旨在用于交互式用途,而不是用于自动化。尝试重定向其标准输出没有意义,因为它没有使用它。
对于自动化,请使用PuTTY软件包中的另一个工具plink.exe
。
这是一个控制台应用程序,因此您可以重定向其标准输出/输入。
试图通过cmd.exe
间接执行应用程序没有任何意义。直接执行。
您还需要重定向标准输入,以便能够将命令提供给Plink。
您必须在调用.Start()
之前提供参数。
您可能也想重定向错误输出(RedirectStandardError
)。尽管请注意,您将需要并行读取输出和错误输出,但这会使代码复杂化。
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();
}
关于c# - 在C#中使用PuTTY运行Unix命令,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27592329/