首页 > 解决方案 > 使用 SSH.NET 响应交互式 shell 提示

问题描述

我想通过 ASP.NET 应用程序创建一个 SFTP 帐户。为了定义它的密码,我需要输入两次

root@localhost:~# passwd fadwa
Enter new password:
Retype new password:
passwd: password updated successfully 

要通过 C# 代码执行此操作,我在这里咨询了很多解决方案后尝试了以下方法,但它不起作用。

using (var client = new SshClient("xx.xxx.xxx.xxx", 22, "root", "********"))
{
    client.Connect();
    ShellStream shellStream = client.CreateShellStream(string.Empty, 0, 0, 0, 0, 0);
    StreamWriter stream = new StreamWriter(shellStream);
    StreamReader reader = new StreamReader(shellStream);
    stream.WriteLine("passwd fadwa"); //It displays -1
    stream.WriteLine("fadwa");
    stream.WriteLine("fadwa");
    Console.WriteLine(reader.Read());    // It displays -1     
    client.Disconnect();
}

StreamWriter即使没有直接使用 but我也试过了:

shellStream.WriteLine("passwd fadwa\n" + "fadwa\n" + "fadwa\n");
while (true) Console.WriteLine(shellStream.Read()); 

shellStream.WriteLine("passwd fadwa");
shellStream.WriteLine("fadwa");
shellStream.WriteLine("fadwa"); 
while (true) Console.WriteLine(shellStream.Read()); 

我得到了这个,它卡在那里! 控制台上显示的输出的屏幕截图

有什么建议为什么它不起作用或其他解决方案?我想我已经尝试过第二种解决方案并且它有效,但不是现在。

标签: .netshellsshsftpssh.net

解决方案


您可能必须在提示出现后才发送输入。如果您过早发送输入,它会被忽略。

一个蹩脚的解决方案就像:

shellStream.WriteLine("passwd fadwa");
Thread.Sleep(100);
shellStream.WriteLine("fadwa");
Thread.Sleep(100);
shellStream.WriteLine("fadwa"); 

更好的解决方案是在发送密码之前等待提示 -expect例如:

shellStream.WriteLine("passwd fadwa");
shellStream.Expect("Enter new password:");
shellStream.WriteLine("fadwa");
shellStream.Expect("Retype new password:");
shellStream.WriteLine("fadwa");

通常,自动化 shell 总是容易出错,应该避免。


推荐阅读