使用SSH.NET连接服务器遇Connection reset by peer异常求助
问题描述
使用SSH.NET连接两台服务器时,其中一台可正常运行,但连接另一台时抛出Connection reset by peer异常。已通过CLI执行ssh user@host命令,用相同密钥可正常连接两台服务器。
错误信息
Unhandled exception. Renci.SshNet.Common.SshConnectionException: Connection reset by peer ---> System.Net.Sockets.SocketException (104): Connection reset by peer at System.Net.Sockets.Socket.Receive(Byte[] buffer, Int32 offset, Int32 size, SocketFlags socketFlags) at Renci.SshNet.Abstractions.SocketAbstraction.Read(Socket socket, Byte[] buffer, Int32 offset, Int32 size, TimeSpan timeout) at Renci.SshNet.Session.TrySocketRead(Byte[] buffer, Int32 offset, Int32 length) at Renci.SshNet.Session.ReceiveMessage() at Renci.SshNet.Session.MessageListener() --- End of inner exception stack trace --- at Renci.SshNet.Session.WaitOnHandle(WaitHandle waitHandle, TimeSpan timeout) at Renci.SshNet.Session.WaitOnHandle(WaitHandle waitHandle) at Renci.SshNet.Session.Connect() at Renci.SshNet.BaseClient.CreateAndConnectSession() at Renci.SshNet.BaseClient.Connect()
代码示例
var keyStr = File.ReadAllText("/home/me/.ssh/id_rsa"); PrivateKeyFile privateKey = null; using (var keystrm = new MemoryStream(Encoding.ASCII.GetBytes(keyStr))) { privateKey = new PrivateKeyFile(keystrm); } var keyFiles = new[] { privateKey }; var methods = new List<AuthenticationMethod>(); methods.Add(new PrivateKeyAuthenticationMethod("me", keyFiles)); var con = new ConnectionInfo("...", 22, "root", methods.ToArray()); using var sshClient = new SshClient(con); sshClient.Connect();
排查与解决思路
- 修正用户名不匹配问题:代码中
PrivateKeyAuthenticationMethod使用的用户名是"me",但ConnectionInfo里的用户名是"root",而CLI连接用的是user@host。SSH密钥认证与用户绑定,服务器端authorized_keys通常存储在对应用户的.ssh目录下,需确保代码中ConnectionInfo的用户名和CLI连接时一致。 - 修复密钥编码问题:用
Encoding.ASCII读取密钥文件可能导致编码错误,建议直接读取字节流避免编码问题:var keyBytes = File.ReadAllBytes("/home/me/.ssh/id_rsa"); using (var keystrm = new MemoryStream(keyBytes)) { privateKey = new PrivateKeyFile(keystrm); } - 添加超时与调试日志:设置连接超时并启用错误日志,便于排查连接过程中的细节:
con.Timeout = TimeSpan.FromSeconds(30); sshClient.ErrorOccurred += (sender, e) => Console.WriteLine($"SSH Error: {e.Exception.Message}"); - 检查服务器SSH配置:
- 确认目标服务器
sshd_config中PermitRootLogin是否允许root用户登录,若CLI用非root用户,代码中也需保持一致。 - 若服务器限制了SSH算法,可手动指定支持的密钥交换算法:
var con = new ConnectionInfo("...", 22, "me", new[] { new PrivateKeyAuthenticationMethod("me", keyFiles) }) { KeyExchangeAlgorithms = new List<string> { "diffie-hellman-group-exchange-sha256" } };
- 确认目标服务器
内容的提问来源于stack exchange,提问作者user5405648
相关产品推荐
相关产品推荐

