在Ubuntu中,要实现SSH自动重连,可以使用autossh
工具。autossh
是一个自动重连SSH会话的工具,它可以在连接断开时自动重新建立连接。以下是安装和使用autossh
的步骤:
autossh
:打开终端,运行以下命令来安装autossh
:
sudo apt-get update
sudo apt-get install autossh
autossh
建立连接:使用autossh
建立连接时,需要指定一个本地端口(例如:2222),该端口将转发到远程服务器的SSH端口(通常是22)。同时,可以使用-M
选项指定一个监控端口(例如:0表示不使用监控端口)。
autossh -M 0 -o "ServerAliveInterval 30" -o "ServerAliveCountMax 3" -p 2222 user@remote_host
其中:
-M 0
:不使用监控端口。-o "ServerAliveInterval 30"
:每30秒发送一次保活信号,以检测连接是否正常。-o "ServerAliveCountMax 3"
:如果连续3次没有收到响应,将断开连接并尝试重新连接。-p 2222
:本地端口2222转发到远程服务器的SSH端口。user@remote_host
:远程服务器的用户名和地址。要将autossh
设置为开机自启动,可以创建一个systemd服务。首先,创建一个新的服务文件:
sudo nano /etc/systemd/system/autossh.service
然后,将以下内容粘贴到文件中(请根据实际情况修改用户、远程主机和端口):
[Unit]
Description=AutoSSH service
After=network.target
[Service]
Type=simple
User=username
ExecStart=/usr/bin/autossh -M 0 -o "ServerAliveInterval 30" -o "ServerAliveCountMax 3" -p 2222 username@remote_host
Restart=always
[Install]
WantedBy=multi-user.target
保存并关闭文件。接下来,启用并启动autossh
服务:
sudo systemctl enable autossh.service
sudo systemctl start autossh.service
现在,autossh
将在系统启动时自动运行,并在连接断开时自动重连。
注意:请确保远程服务器允许使用指定的本地端口(例如:2222)进行连接。如果需要,可以在远程服务器的/etc/ssh/sshd_config
文件中添加以下配置:
AllowTcpForwarding yes
GatewayPorts yes
然后重启SSH服务:
sudo systemctl restart ssh