sudo nano /etc/ssh/sshd_config
添加或修改以下参数:
ClientAliveInterval 60
ClientAliveCountMax 3
TCPKeepAlive yes
解释:
- ClientAliveInterval 60
:服务器每60秒向客户端发送保持活动消息
- ClientAliveCountMax 3
:如果3次保持活动消息无响应,则断开连接
- TCPKeepAlive yes
:启用TCP保持活动机制
重启SSH服务:
sudo systemctl restart sshd
安装tmux:
sudo apt install tmux # Debian/Ubuntu
sudo yum install tmux # CentOS/RHEL
基本用法:
tmux new -s session_name # 创建新会话
Ctrl+b d # 分离会话
tmux attach -t session_name # 重新连接会话
编辑或创建~/.ssh/config
:
Host *
ServerAliveInterval 60
ServerAliveCountMax 3
TCPKeepAlive yes
ControlMaster auto
ControlPath ~/.ssh/control:%h:%p:%r
ControlPersist 4h
解释:
- ServerAliveInterval
:客户端每60秒发送保持活动消息
- ControlMaster/ControlPath/ControlPersist
:启用连接共享和持久化
安装autossh:
sudo apt install autossh # Debian/Ubuntu
sudo yum install autossh # CentOS/RHEL
使用示例:
autossh -M 0 -o "ServerAliveInterval 60" -o "ServerAliveCountMax 3" user@host
安装mosh:
sudo apt install mosh # Debian/Ubuntu
sudo yum install mosh # CentOS/RHEL
使用:
mosh user@host
优点: - 基于UDP,对网络变化更鲁棒 - 本地回显,延迟更低 - 自动重连
对于特别不稳定的网络,考虑: 1. 建立VPN连接到目标网络 2. 使用跳板机作为中间节点 3. 云服务商提供的会话管理器(如AWS Session Manager)
script
命令记录会话通过以上方法,您可以显著提高SSH会话的稳定性,确保长时间远程管理任务的连续性。