Loading

使用ssh创建tunnel并守护

需求

服务器仅开放了ssh作为公网入口,希望经由ssh端口转发访问内网端口业务。
最好能写成类似服务形式,可以守护。

实现

使用ssh建立后台连接并设置ServerAliveInterval=60防止断开。
我穿透的是tinyproxy提供的http代理端口,使用httping验证内网ip能否连通。

#!/bin/bash
local_port=8888
key_path=/home/ubuntu/ssh_key
cd ~/tunnel
pwd=`pwd`
PIDS=`ps -ef| grep ssh |grep $local_port | awk '{print $2}'`
if [ -z "$PIDS" ]; then  #check if tunnel exists
    #if not exist, create the tunnel
    ssh jump@123.45.67.8 -p 12345 -o ServerAliveInterval=60 -i ${key_path} -C -f -N -g -L ${local_port}:127.0.0.1:8888
    echo "start tunnel:`date`" >> $pwd/log.txt
else
    #if tunnel exist, check connectivity
    httping -x 127.0.0.1:8888 -c 1 -t 1 -q 192.168.1.1
    if [ $? -ne 0 ]; then
        #if not connectable, kill and re-connect the tunnel
        kill -9 $PIDS
	ssh jump@123.45.67.8 -p 12345 -o ServerAliveInterval=60 -i ${key_path} -C -f -N -g -L ${local_port}:127.0.0.1:8888
        echo "kill and start tunnel:`date`" >> $pwd/log.txt
    fi
fi
#echo "checked :`date`" >> $pwd/log.txt

守护

这边采用crontab进行守护方便维护
每天18:00 - 23:00整点进行检查

crontab -e
# m h  dom mon dow   command
0 18-23 * * * /home/ubuntu/tunnel/daemon.sh
posted @ 2023-09-05 14:11  azureology  阅读(57)  评论(0编辑  收藏  举报