我已经看到了有关此错误的其他线程,但是我随机遇到此错误。在30个连接中,有12个出现此错误。试图了解原因以及可能的解决方案。
using (SftpClient client = new SftpClient(sftpHost, sftpPort, sftpUser, sftpPassword))
{
client.Connect();
}
Run Code Online (Sandbox Code Playgroud)
抛出此异常:
Renci.SshNet.Common.SshConnectionException:服务器响应不包含SSH协议标识
这可能听起来微不足道,但我已经尝试过 Renci.SshNet.Async 包,它没有任何问题。以下可能是解决方案或替代解决方案问题的原因。
这里的示例由 WinSCP https://winscp.net/eng/docs/library_examples提供。
我的测试示例是:
这只是一个playground示例,看看东西是否正在运行,在生产中使用时,请修改它。更要感谢@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;
}
}
Run Code Online (Sandbox Code Playgroud)
这个例子应该返回一个目录列表
相关链接:
老实说,没有人知道这种行为的确切原因。
作为可能的解决方案,有些人建议创建一个计数器循环来重试连接,这表明它解决了他们的问题:
int attempts = 0;
do
{
try
{
client.Connect();
}
catch (Renci.SshNet.Common.SshConnectionException e)
{
attempts++;
}
} while (attempts < _connectiontRetryAttempts && !client.IsConnected);
Run Code Online (Sandbox Code Playgroud)
另一个建议是将 IP 地址添加到hosts.allow服务器上的文件中,这样您也可以朝该方向进行检查。
正如我所说,对于这种行为完全没有可能的解释。