随机获取 Renci.SshNet.SftpClient.Connect 抛出 SshConnectionException

问题描述 投票:0回答:3

我看过有关此错误的其他线程,但我随机遇到此错误。在 30 个连接中,有 12 个出现此错误。尝试了解这是为什么,以及可能的解决方案是什么。

using (SftpClient client = new SftpClient(sftpHost, sftpPort, sftpUser, sftpPassword))
{
    client.Connect();
}

抛出此异常:

Renci.SshNet.Common.SshConnectionException:服务器响应不包含 SSH 协议标识

c# sftp ssh.net
3个回答
9
投票

这可能听起来微不足道,但我已经尝试过 Renci.SshNet.Async 包,它的工作没有任何问题。以下可能是问题的原因以及解决方案或替代解决方案。

  1. Renci.SshNet.Async 可能存在在特定环境或特定组合中出现的错误或问题。有些人在这里提到了同样的问题,没有解决方案https://github.com/sshnet/SSH.NET/issues/377
  2. 有些人遇到了同样的问题并提到了解决方案,一种是重试n多次Renci.SshNet:“服务器响应不包含ssh协议标识”
  3. 问题不在于您的客户端,而或多或少在于您的主机。这可能是很多事情或问题。
  4. 最后我会尝试使用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;
    }
}

此示例应返回目录列表

相关链接:


1
投票

说实话,没有人知道这种行为的确切原因。

作为一种可能的解决方案,有些人建议创建一个计数器循环来重试连接,这表明它解决了他们的问题:

int attempts = 0;
do
{
    try
    {
        client.Connect();
    }
    catch (Renci.SshNet.Common.SshConnectionException e)
    {
        attempts++;
    }
} while (attempts < _connectiontRetryAttempts && !client.IsConnected);

另一个建议是将 IP 地址添加到服务器上的

hosts.allow
文件中,这样您也可以朝该方向检查。

正如我所说,对于这种行为完全没有可能的解释。


0
投票

我知道这是一个旧线程,但为了帮助其他偶然发现它的人,就像我一样,我在连接到 Ubiquiti 无线电时遇到了这个问题。问题是由于我的代码中的错误,我同时运行了许多与无线电的 ssh 会话。我认为客户端或服务器资源匮乏。修复我的代码中的错误使错误消失。

© www.soinside.com 2019 - 2024. All rights reserved.