c# - 随机获取 Renci.SshNet.SftpClient.Connect 抛出 SshConnectionException
问题描述
我已经看到有关此错误的其他线程,但我随机遇到此错误。在 30 个连接中,有 12 个出现此错误。试图理解为什么会这样,以及可能的解决方案是什么。
using (SftpClient client = new SftpClient(sftpHost, sftpPort, sftpUser, sftpPassword))
{
client.Connect();
}
抛出此异常:
Renci.SshNet.Common.SshConnectionException:服务器响应不包含 SSH 协议标识
解决方案
这可能听起来微不足道,但我已经尝试了 Renci.SshNet.Async 包,它没有任何问题。以下可能是解决方案或替代解决方案问题的原因。
- Renci.SshNet.Async 可能存在特定环境或特定组合中出现的错误或问题。有些人在这里提到了同样的问题,没有解决方案https://github.com/sshnet/SSH.NET/issues/377
- 有的遇到同样的问题,提了一个解决办法,一个是重试n次 Renci.SshNet :“server response does not contain ssh protocol Identification”
- 问题不在于您的客户,而或多或少在于您的主机。它可以是很多事情或问题。
- 最后我会尝试使用WinSCP,它也是 .net ( nuget ) 的公认库。我自己也尝试过,到目前为止从未遇到任何问题。我建议您获取它并尝试将其作为您当前解决方案的替代品,看看它是否有帮助。如果 WinSCP 有效,则第 1 点有效,如果您遇到与 WinSCP 相同的问题,则第 3 点有效。这样我们就可以得出结论并缩小问题的范围。
此处由 WinSCP https://winscp.net/eng/docs/library_examples提供的示例。
我的测试示例是:
这只是操场上的例子,看看事情是否正在运行,在生产中使用时,请修改它。进一步感谢@MartinPrikry 添加此注释:如果您设置
SshHostKeyFingerprint
正确,则不要设置GiveUpSecurityAndAcceptAnySshHostKey
。
public static int WinSCPListDirectory()
{
try
{
var sessionOptions = new SessionOptions
{
Protocol = Protocol.Sftp,
HostName = "xxx.xxx.xxx.xxx",
UserName = "username",
Password = "password",
SshHostKeyFingerprint = "ssh-rsa 2048 xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx",
GiveUpSecurityAndAcceptAnySshHostKey = true
};
using (var session = new Session())
{
session.Open(sessionOptions);
var directory = session.ListDirectory("/var/www");
foreach (RemoteFileInfo fileInfo in directory.Files)
{
Console.WriteLine(
"{0} with size {1}, permissions {2} and last modification at {3}",
fileInfo.Name, fileInfo.Length, fileInfo.FilePermissions,
fileInfo.LastWriteTime);
}
}
return 0;
}
catch (Exception e)
{
Console.WriteLine("Error: {0}", e);
return 1;
}
}
此示例应返回目录列表
相关链接:
推荐阅读
- android - 无法正确配置 expo 应用程序`无法读取配置:/app.config.js`
- html - 如何计算 C++ 中的 HTML 标签?
- unity3d - 2DLights - 通用渲染管线 - 轻量级 RP
- docker - docker-compose 端口未映射;日志显示应用程序正在运行
- python - 使用 str.contains 时有没有办法排除特定的子字符串?
- jpa - 使用 Criteria Builder 对多列进行 JPA 搜索查询
- php - Laravel - 嵌套关系,按最近的嵌套排序父模型
- c++ - 在 C++ 中将数据传递给线程的好方法是什么?
- javascript - 我在饼图中得到错误的百分比
- docker - Github 操作 Pylint 步骤无法使用测试作业创建目录