这里记录了如何配置 Linux 系统下 ssh 隧道的 service 步骤。

第一步:添加 systemd 的 service 文件

内容如下:

$ cat /usr/lib/systemd/system/ssh-tunnel.service
[Unit]
Description=Setup a secure tunnel to ssh server
After=network.target

[Service]
Environment="LOCAL_ADDR=localhost"
EnvironmentFile=/etc/default/ssh-tunnel
ExecStart=/usr/bin/ssh -NT -o ServerAliveInterval=60 -o ExitOnForwardFailure=yes -L ${LOCAL_ADDR}:${LOCAL_PORT}:localhost:${REMOTE_PORT} -i /home/liqiang.io/.ssh/id_rsa ${TARGET}

# Restart every >2 seconds to avoid StartLimitInterval failure
RestartSec=5
Restart=always

[Install]
WantedBy=multi-user.target

这里有几点需要非常注意:

第二步:配置参数

$ cat /etc/default/ssh-tunnel
TARGET=jupiter
LOCAL_ADDR=0.0.0.0
LOCAL_PORT=20022
REMOTE_PORT=22

第三步:运行起来

$ systemctl start ssh-tunnel
$ systemctl status ssh-tunnel

【可选】第四步:开机自启

$ systemctl enable ssh-tunnel

Reference