我看过有关此错误的其他线程,但我随机遇到此错误。在 30 个连接中,有 12 个出现此错误。尝试了解这是为什么,以及可能的解决方案是什么。
using (SftpClient client = new SftpClient(sftpHost, sftpPort, sftpUser, sftpPassword))
{
client.Connect();
}
抛出此异常:
Renci.SshNet.Common.SshConnectionException:服务器响应不包含 SSH 协议标识
这可能听起来微不足道,但我已经尝试过 Renci.SshNet.Async 包,它的工作没有任何问题。以下可能是问题的原因以及解决方案或替代解决方案。
这里是 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;
}
}
此示例应返回目录列表
相关链接:
说实话,没有人知道这种行为的确切原因。
作为一种可能的解决方案,有些人建议创建一个计数器循环来重试连接,这表明它解决了他们的问题:
int attempts = 0;
do
{
try
{
client.Connect();
}
catch (Renci.SshNet.Common.SshConnectionException e)
{
attempts++;
}
} while (attempts < _connectiontRetryAttempts && !client.IsConnected);
另一个建议是将 IP 地址添加到服务器上的
hosts.allow
文件中,这样您也可以朝该方向检查。
正如我所说,对于这种行为完全没有可能的解释。
我知道这是一个旧线程,但为了帮助其他偶然发现它的人,就像我一样,我在连接到 Ubiquiti 无线电时遇到了这个问题。问题是由于我的代码中的错误,我同时运行了许多与无线电的 ssh 会话。我认为客户端或服务器资源匮乏。修复我的代码中的错误使错误消失。