.net - 使用 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());
有什么建议为什么它不起作用或其他解决方案?我想我已经尝试过第二种解决方案并且它有效,但不是现在。
解决方案
您可能必须在提示出现后才发送输入。如果您过早发送输入,它会被忽略。
一个蹩脚的解决方案就像:
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 总是容易出错,应该避免。
推荐阅读
- typescript - 无法创建父类
- salesforce - 为什么工作流规则不适用于 Salesforce?
- node.js - 幻影安装失败 EACCES:权限被拒绝 - AWS - NodeJS - 无法部署更新的应用程序
- spring-boot - 在 Spring Boot 指标中计算 AsyncResponse 调用
- php - Laravel 有时显示 404 not found 页面
- jenkins-pipeline - 我想根据带有项目名称和状态的 jenkins 构建来更改工作流状态
- jquery - JQuery - on() Keyup Validation 不起作用
- qt - 有没有办法在占位符文本 QML 中为特定单词着色?
- python - 为什么我的 on_message 事件打印日志两次?
- spring - 使用 NamedParameterJdbcTemplate 插入批处理并返回完整对象