插件窝 干货文章 Connection closed by foreign

Connection closed by foreign

SSH 检查 断开 超时 520    来源:    2025-05-12

这个错误提示 "Connection closed by foreign" 通常出现在SSH或网络连接场景中,表示远程主机主动断开了连接。以下是可能原因和解决方案:

可能原因: 1. 远程主机配置了空闲超时断开 2. 网络不稳定或中间设备断开 3. 服务器负载过高主动断开 4. SSH服务端配置限制 5. 防火墙/安全组策略中断

解决方案:

  1. 保持连接活跃(SSH客户端配置):
# 在~/.ssh/config中添加:
Host *
    ServerAliveInterval 60
    ServerAliveCountMax 5
  1. 检查服务端超时设置(需管理员权限):
# 查看SSH服务端超时配置
sudo grep -i "ClientAlive" /etc/ssh/sshd_config

# 如果需要修改(示例设置为每300秒检测一次,最多3次不响应才断开):
sudo sed -i 's/^#*ClientAliveInterval.*/ClientAliveInterval 300/' /etc/ssh/sshd_config
sudo sed -i 's/^#*ClientAliveCountMax.*/ClientAliveCountMax 3/' /etc/ssh/sshd_config
sudo systemctl restart sshd
  1. 网络诊断:
# 检查网络稳定性
ping -c 10 your_server_ip
traceroute your_server_ip

# 检查是否有丢包
mtr --report your_server_ip
  1. 检查系统资源:
# 查看服务器负载
ssh user@host "uptime; free -h"

# 检查SSH连接数
ssh user@host "netstat -an | grep :22 | wc -l"
  1. 防火墙检查:
# 查看防火墙日志(CentOS)
sudo grep DROP /var/log/audit/audit.log

# Ubuntu/Debian
sudo grep DROP /var/log/ufw.log
  1. 其他尝试:

- 使用不同网络环境测试 - 尝试SSH的-v/-vvv参数查看详细日志:

ssh -vvv user@host
  • 更换SSH端口测试

如果是生产环境频繁出现此问题,建议检查: 1. 中间网络设备(如负载均衡器、WAF)的超时设置 2. 服务器TCP keepalive设置 3. 系统日志(/var/log/messages, /var/log/syslog)中的相关错误

需要更具体的解决方案,请提供: - 完整的错误信息 - 出现场景(如执行特定操作时) - 服务器操作系统和SSH版本信息