使用autossh做端口转发


有时我们会遇上需要代理端口的情况, 此时我们可以通过ssh工具来代理端口 如:

1
ssh -C -f -N -g -L 3306:10.1.12.126:3306 root@10.1.12.126

这个命令会把到本机的3306端口的请求转发到10.1.12.126,但是随着时间的推移,在长时间没有新消息时,ssh的通道会断开,为了解决这个问题, 我们可以使用autossh工具

首先安装autossh

1
2
3
4
5
wget http://www.harding.motd.ca/autossh/autossh-1.4e.tgz --no-check-certificate
tar -xf autossh-1.4e.tgz
cd autossh-1.4e/
./configure
make

执行完以上命令后, 我们会得到autossh的二进制文件

1
mv autossh  /usr/bin/autossh

这个工具使用方式与ssh 类似:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
usage: autossh [-V] [-M monitor_port[:echo_port]] [-f] [SSH_OPTIONS]

-M specifies monitor port. May be overridden by environment
variable AUTOSSH_PORT. 0 turns monitoring loop off.
Alternatively, a port for an echo service on the remote
machine may be specified. (Normally port 7.)
-f run in background (autossh handles this, and does not
pass it to ssh.)
-V print autossh version and exit.

Environment variables are:
AUTOSSH_GATETIME - how long must an ssh session be established
before we decide it really was established
(in seconds). Default is 30 seconds; use of -f
flag sets this to 0.
AUTOSSH_LOGFILE - file to log to (default is to use the syslog
facility)
AUTOSSH_LOGLEVEL - level of log verbosity
AUTOSSH_MAXLIFETIME - set the maximum time to live (seconds)
AUTOSSH_MAXSTART - max times to restart (default is no limit)
AUTOSSH_MESSAGE - message to append to echo string (max 64 bytes)
AUTOSSH_PATH - path to ssh if not default
AUTOSSH_PIDFILE - write pid to this file
AUTOSSH_POLL - how often to check the connection (seconds)
AUTOSSH_FIRST_POLL - time before first connection check (seconds)
AUTOSSH_PORT - port to use for monitor connection
AUTOSSH_DEBUG - turn logging to maximum verbosity and log to
stderr

上面的需求我们可以通过autossh 用如下命令来实现

1
autossh -M 0 -o "ServerAliveInterval 10" -o "ServerAliveCountMax 1" -NgL 3306:10.1.12.126:3306 root@10.1.12.126

进一步调整,使用systemd来进行管理这个代理

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
cat >/usr/lib/systemd/system/autossh.service <<EOF
[Unit]
Description=AutoSSH tunnel service for vnc-server
After=network.target

[Service]
Environment="AUTOSSH_GATETIME=0"
ExecStart=/usr/bin/autossh -M 0 -o "ServerAliveInterval 10" \
-o "ServerAliveCountMax 1" -NgL 3306:10.1.12.126:3306 root@10.1.12.126
[Install]
WantedBy=multi-user.target
EOF

systemctl daemon-reload
systemctl enable autossh --now