【问题标题】:SSH.NET C# send Yes or No to linux serverSSH.NET C# 向 linux 服务器发送 Yes 或 No
【发布时间】:2025-12-03 15:20:07
【问题描述】:

我想从 C# 程序在 linux 服务器上执行一个脚本,我有一个示例代码如下。

var ssh = new SshClient("ip", "user", "password");
var cmd = ssh .CreateCommand("./executescript");
cmd.BeginExecute();
var reader = new StreamReader(cmd.OutputStream);
var result = reader.ReadToEnd();

但我无法完成脚本的执行,因为它会问一个问题,例如“你愿意这样做吗?是或否',如何从 C# 向 linux 发送是或否?

谁能给我一些建议?或者有什么建议?

【问题讨论】:

  • 你试过ssh.RunCommand("yes") 吗?它可能会起作用。
  • 你好,它不起作用...我发现ssh expect可以解决这个问题。非常感谢。

标签: c# linux ssh


【解决方案1】:

试试这个代码

            SshShell shell = new SshShell(<host>, username, pass);
            shell.Connect();
            shell.RemoveTerminalEmulationCharacters = true;
            string outputt = shell.Expect(new Regex(@"[$#>]"));
            shell.WriteLine("cd <Path> ");
            outputt = shell.Expect(new Regex(@"[$#>]"));
            shell.WriteLine("nohup bash executescript.sh & ");
            outputt = shell.Expect(new Regex(@"[$#>]"));
            shell.WriteLine("exit");
            outputt = shell.Expect(new Regex(@"[$#>]"));

            shell.Close();

它对我有用。

【讨论】: