在C#中使用PuTTY运行Unix命令 [英] Run Unix commands using PuTTY in C#
问题描述
我正在尝试使用C#在PuTTY中运行Unix命令.我有下面的代码.但是代码不起作用.我无法打开腻子.
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";
}
推荐答案
-
putty.exe
是一个GUI应用程序.它旨在用于交互用途,而不是用于自动化.尝试重定向其标准输出是没有意义的,因为它没有使用它.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.试图通过
cmd.exe
间接执行应用程序是没有意义的.直接执行.There's no point trying to execute an application indirectly via the
cmd.exe
. Execute it directly.您还需要重定向标准输入,以便能够将命令提供给Plink.
You need to redirect standard input too, to be able to feed commands to the Plink.
您必须在调用
.Start()
之前提供参数.You have to provide arguments before calling the
.Start()
.您可能还希望重定向错误输出(
RedirectStandardError
).尽管请注意,您将需要并行读取输出和错误输出,但这会使代码复杂化.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(); }
这篇关于在C#中使用PuTTY运行Unix命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!