SSH连接超时中断是常见问题,通常由网络不稳定、服务器配置或客户端设置引起。以下是几种有效的解决方法:
sudo vim /etc/ssh/sshd_config
添加或修改以下参数:
ClientAliveInterval 60 # 服务器每60秒向客户端发送一次保活消息
ClientAliveCountMax 3 # 连续3次无响应才断开连接
TCPKeepAlive yes # 启用TCP保活机制
重启SSH服务使配置生效:
sudo systemctl restart sshd
vim ~/.ssh/config
添加以下内容:
Host *
ServerAliveInterval 60 # 客户端每60秒向服务器发送一次保活消息
ServerAliveCountMax 3 # 连续3次无响应才断开连接
TCPKeepAlive yes
在连接服务器后立即启动终端复用器:
tmux new -s mysession
# 或
screen -S mysession
autossh -M 0 -o "ServerAliveInterval 60" -o "ServerAliveCountMax 3" user@host
# 临时设置
sudo sysctl -w net.ipv4.tcp_keepalive_time=60
sudo sysctl -w net.ipv4.tcp_keepalive_intvl=10
sudo sysctl -w net.ipv4.tcp_keepalive_probes=6
# 永久设置
echo "net.ipv4.tcp_keepalive_time = 60" | sudo tee -a /etc/sysctl.conf
echo "net.ipv4.tcp_keepalive_intvl = 10" | sudo tee -a /etc/sysctl.conf
echo "net.ipv4.tcp_keepalive_probes = 6" | sudo tee -a /etc/sysctl.conf
sudo sysctl -p
使用-v参数查看详细连接日志,帮助诊断问题:
ssh -v user@host
对于NAT环境,可能需要调整路由器/防火墙的超时设置
考虑使用VPN或专用网络连接减少中间网络设备的影响
以上方法可根据实际情况组合使用,通常调整ClientAliveInterval/ServerAliveInterval参数即可解决大部分超时问题。