ubuntu

Ubuntu SSH如何自动重连

小樊
56
2025-06-23 04:16:15
栏目: 智能运维

在Ubuntu中,要实现SSH自动重连,可以使用autossh工具。autossh是一个自动重连SSH会话的工具,它可以在连接断开时自动重新建立连接。以下是安装和使用autossh的步骤:

  1. 安装autossh

打开终端,运行以下命令来安装autossh

sudo apt-get update
sudo apt-get install autossh
  1. 使用autossh建立连接:

使用autossh建立连接时,需要指定一个本地端口(例如:2222),该端口将转发到远程服务器的SSH端口(通常是22)。同时,可以使用-M选项指定一个监控端口(例如:0表示不使用监控端口)。

autossh -M 0 -o "ServerAliveInterval 30" -o "ServerAliveCountMax 3" -p 2222 user@remote_host

其中:

  1. 设置开机自启动:

要将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

0
看了该问题的人还看了