You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring应用通过Open SSH在Azure虚拟机间传文件:JSch连接失败

解决JSch连接Azure虚拟机SFTP时出现Connection reset的问题

针对你用JSch连接Azure VM时遇到的com.jcraft.jsch.JSchException: Session.connect: java.net.SocketException: Connection reset错误,从Azure配置、JSch参数、SSH服务三个维度给出排查和解决方法:

一、检查Azure虚拟机的网络与安全配置

  • 确认网络安全组(NSG)入站规则:必须允许应用服务器IP访问VM的22端口(SSH默认端口),如果用了自定义SSH端口,要对应开放该端口。
  • 验证VM的访问地址:dto.getVirtualHost()必须是VM的公共IP地址或正确的DNS名称,避免拼写错误。
  • 若使用自定义SSH端口,必须在getSession方法中指定端口,比如jsch.getSession(user, host, 2222)(2222为自定义端口)。

二、修正JSch的配置参数

默认的JSch配置可能和Azure SSH服务不兼容,建议添加以下关键配置:

Properties config = new Properties();
// 开发环境临时关闭主机密钥检查(生产环境建议提前配置已知主机密钥)
config.put("StrictHostKeyChecking", "no");
// 明确指定使用密码认证,避免其他认证方式干扰
config.put("PreferredAuthentications", "password");
// 支持Azure常用的SSH密钥算法
config.put("server_host_key", "ssh-rsa,ecdsa-sha2-nistp256");
// 设置连接超时时间,避免无限等待
config.put("connection.timeout", "30000");

同时,在connect方法中指定超时时间:

session.connect(30000); // 会话连接超时30秒
channel.connect(10000); // SFTP通道连接超时10秒

三、检查Azure虚拟机的SSH服务状态

  • 登录VM,确认sshd服务正在运行:执行systemctl status sshd(Linux系统),若未运行则启动服务:systemctl start sshd。
  • 检查sshd配置文件/etc/ssh/sshd_config:确保PasswordAuthentication yes(允许密码登录),若设为no则密码方式无法连接。
  • 确认sshd监听端口:执行netstat -tulpn | grep sshd,检查监听端口是否和你使用的一致。

四、网络连通性测试

  • 在应用服务器上执行ping <VM公共IP>,确认能正常连通,若不通则排查路由或防火墙问题。
  • 用telnet <VM主机> 22测试端口连通性,若无法连接则说明端口未开放或被拦截。

修正后的完整示例代码

JSch jsch = new JSch();
// 若使用自定义端口,替换第三个参数为对应端口号
Session session = jsch.getSession(dto.getUserName(), dto.getVirtualHost(), 22);
session.setPassword(dto.getPassword());

Properties config = new Properties();
config.put("StrictHostKeyChecking", "no");
config.put("PreferredAuthentications", "password");
config.put("server_host_key", "ssh-rsa,ecdsa-sha2-nistp256");
config.put("connection.timeout", "30000");

session.setConfig(config);
try {
    session.connect(30000);
    ChannelSftp channel = (ChannelSftp) session.openChannel("sftp");
    channel.connect(10000);
    
    // 执行文件传输操作,例如上传本地文件到VM
    // channel.put("/local/path/file.txt", "/remote/path/file.txt");
    
    channel.disconnect();
    session.disconnect();
} catch (JSchException | SftpException e) {
    e.printStackTrace();
    // 这里添加异常处理逻辑
}

内容的提问来源于stack exchange,提问作者Dipanjan Baidya

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 10:47:36