c#如何调用用plink登录ssh并且获取pwd命令结果

2023-06-06  本文已影响0人  sysdzw

可以使用Process类和plink命令来登录SSH,并且获取pwd命令的结果。

using System;
using System.Diagnostics;

namespace SSHTest
{
    class Program
    {
        static void Main(string[] args)
        {
            string sshHost = "your-ssh-hostname";
            string sshUser = "your-ssh-username";
            string sshPassword = "your-ssh-password";
            string sshCommand = "pwd";

            ProcessStartInfo psi = new ProcessStartInfo();
            psi.FileName = "plink.exe";
            psi.Arguments = String.Format("-ssh {0}@{1} -pw {2} {3}", sshUser, sshHost, sshPassword, sshCommand);
            psi.RedirectStandardOutput = true;
            psi.UseShellExecute = false;

            Process process = new Process();
            process.StartInfo = psi;
            process.Start();

            string output = process.StandardOutput.ReadToEnd();
            Console.WriteLine(output);

            process.WaitForExit();
        }
    }
}

在上述代码中,我们使用plink命令登录SSH,并执行pwd命令来获取当前工作目录的路径。我们使用ProcessStartInfo类来设置命令行参数和重定向标准输出。然后,我们创建一个新的进程并启动它。最后,我们等待进程退出,并读取并打印标准输出。

请注意,该示例代码需要在Windows操作系统中运行,并且需要将plink.exe文件添加到系统路径中,或者将其放置在与可执行文件相同的目录中。你还需要将sshHost,sshUser和sshPassword变量替换为你的SSH登录凭据和主机名。

上一篇 下一篇

猜你喜欢

热点阅读