【问题标题】:Run Unix commands using PuTTY in C# [duplicate]在 C# 中使用 PuTTY 运行 Unix 命令 [重复]
【发布时间】:2021-11-10 16:30:10
【问题描述】:

我正在尝试使用 C# 在 PuTTY 中运行 Unix 命令。我有下面的代码。但是代码不起作用。我无法打开 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";
}

【问题讨论】:

标签: c# .net ssh putty


【解决方案1】:

首先,一般来说,您最好使用原生 .NET SSH 库,例如 SSH.NET,而不是运行外部应用程序。

How to run commands on SSH server in C#?


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

【讨论】:

    【解决方案2】:

    这应该可行:

        static void Main(string[] args)
        {
            ProcessStartInfo cmd = new ProcessStartInfo();
            cmd.FileName = @"C:\Users\win7\Desktop\putty.exe";
            cmd.UseShellExecute = false;
            cmd.RedirectStandardInput = false;
            cmd.RedirectStandardOutput = true;
            cmd.Arguments = "-ssh mahi@192.168.37.129 22 -pw mahi";
            using (Process process = Process.Start(cmd))
            {
                process.WaitForExit();
            }
        }
    

    【讨论】:

    • 虽然代码确实执行了 PuTTY,但它如何让你执行命令?
    • 如果你想运行命令,我推荐使用像 SSH.NET 这样的 SSH 库而不是使用 putty。
    猜你喜欢
    • 2016-09-19
    • 1970-01-01
    • 1970-01-01
    • 2014-11-20
    • 1970-01-01
    • 2017-06-16
    • 2014-02-04
    • 2014-12-04
    • 1970-01-01
    相关资源
    最近更新 更多