首页 > 解决方案 > 随机获取 Renci.SshNet.SftpClient.Connect 抛出 SshConnectionException

问题描述

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

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

抛出此异常:

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

标签: c#sftpssh.net

解决方案


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

  1. Renci.SshNet.Async 可能存在特定环境或特定组合中出现的错误或问题。有些人在这里提到了同样的问题,没有解决方案https://github.com/sshnet/SSH.NET/issues/377
  2. 有的遇到同样的问题,提了一个解决办法,一个是重试nRenci.SshNet :“server response does not contain ssh protocol Identification”
  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;
    }
}

此示例应返回目录列表

相关链接:


推荐阅读