使用SSH.Net连接合作方SFTP服务器遇ProtocolError问题求助
解决SSH.NET连接SFTP服务器报错
The connection was closed by the server: Failed to read binary packet data! (ProtocolError) 核心原因
你的代码使用了SSH.NET默认的连接配置,而合作方SFTP服务器的算法套件(密钥交换、加密、MAC等)与SSH.NET 2020.0.2的默认支持列表不兼容,导致握手阶段服务器主动关闭连接。FileZilla支持的算法范围更广,因此可以正常连接。
解决步骤
1. 使用自定义ConnectionInfo配置兼容算法
你当前代码中创建了ConnectionInfo但未实际使用,需基于它配置与服务器兼容的算法套件,替换默认的SftpClient构造函数调用:
var methods = new List<AuthenticationMethod>(); methods.Add(new PasswordAuthenticationMethod(userName, password)); // 配置兼容的SSH算法,参考FileZilla支持的常用套件 var config = new ConnectionConfig(); // 允许的密钥交换算法 config.AllowedKeyExchangeAlgorithms = new List<string> { "ecdh-sha2-nistp256", "ecdh-sha2-nistp384", "ecdh-sha2-nistp521", "diffie-hellman-group-exchange-sha256", "diffie-hellman-group14-sha256", "diffie-hellman-group16-sha512", "diffie-hellman-group18-sha512" }; // 允许的加密算法 config.AllowedEncryptionAlgorithms = new List<string> { "aes256-ctr", "aes192-ctr", "aes128-ctr", "aes256-cbc", "aes192-cbc", "aes128-cbc" }; // 允许的MAC算法 config.AllowedMacAlgorithms = new List<string> { "hmac-sha2-256-etm@openssh.com", "hmac-sha2-512-etm@openssh.com", "hmac-sha2-256", "hmac-sha2-512" }; // 允许的主机密钥算法 config.AllowedHostKeyAlgorithms = new List<string> { "ssh-ed25519", "ecdsa-sha2-nistp256", "ecdsa-sha2-nistp384", "ecdsa-sha2-nistp521", "ssh-rsa", "ssh-dss" }; // 基于自定义配置创建ConnectionInfo var con = new ConnectionInfo(hostName, port, userName, methods.ToArray()) { Config = config }; // 使用配置好的ConnectionInfo初始化SftpClient var sftpClient = new SftpClient(con); sftpClient.Connect();
2. 确认服务器实际使用的算法(可选)
如果上述配置仍不生效,可打开FileZilla的日志查看它与服务器握手时使用的具体算法:
- 打开FileZilla,依次点击
编辑->设置->日志,勾选显示详细日志 - 连接合作方SFTP服务器,查看日志中类似
Key exchange: XXX、Encryption: XXX的条目 - 将这些具体算法添加到上述
ConnectionConfig的对应列表中
3. 尝试升级SSH.NET版本(谨慎操作)
SSH.NET 2020.0.2版本较旧,后续版本扩展了对更多算法的支持。若你的项目允许,可尝试升级到兼容.NET Framework 4.5.2的最新版本(注意:需确认版本兼容性,部分新版本可能不再支持4.5.2)。
内容的提问来源于stack exchange,提问作者Rango
相关产品推荐
相关产品推荐

