Autossh for systemd --- ssh隧道自动加载

autossh 其实是一个ssh的扩展工具。一般应用在ssh 隧道建立/维护中。兼容全部ssh标准指令。可以自动重连服务。

不过,autossh不自带systemd的脚本。这里是修改的一套。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
[Unit]
Description=Keeps an ssh tunnel
After=network-online.target ssh.service
[Service]
User=xxx
RestartSec=3
Restart=always
ExecStart=/usr/bin/autossh -v -nNT -R x.x.x.x:29528:localhost:29527 x.x.x.x
TimeoutStopSec=10
[Install]
WantedBy=multi-user.target

复制到:

1
/etc/systemd/system/autossh.service

使用systemctl控制

1
2
3
sudo systemctl daemon-reload
sudo systemctl start autossh
sudo systemctl status autossh

参考的脚本:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
[Unit]
Description=Keeps an ssh tunnel to %I open
After=network-online.target ssh.service
[Service]
User=tunnel
# no monitoring
Environment="AUTOSSH_PORT=0"
# Disable gatetime behaviour
Environment="AUTOSSH_GATETIME=0"
EnvironmentFile=/etc/default/autossh@%i
RestartSec=3
Restart=always
# -NT Just open the connection and do nothing (not interactive, no tty alloc)
# use /usr/bin/ssh instead of autossh is good as well
ExecStart=/usr/bin/autossh -NT -o "ExitOnForwardFailure=yes" $SSH_OPTIONS ${TARGET_HOST} $FORWARDS
TimeoutStopSec=10
[Install]
WantedBy=multi-user.target