Ssh端口转发脚本
简介
使用autossh工具实现, 功能:
- 开放跳板机端口, 内网通过跳板机访问远程服务器
- 自动重连
- 支持多层跳板机
脚本
安装
yum -y install autossh脚本在跳板机上运行, 主要通过跳板机端口实现转发
#!/bin/bash
# 用于配置ssh隧道转发
export AUTOSSH_POLL=60
export AUTOSSH_PORT=0
function start(){
# 测试1: 开放内网10.0.0.2的10001端口, 远程连接外网192.168.1.2的22端口
autossh -M 0 -o "ExitOnForwardFailure yes" -o "ServerAliveInterval 30" -o "ServerAliveCountMax 3" -fNL 0.0.0.0:10001:192.168.1.2:22 root@10.0.0.2
# 测试2: 开放内网10.0.0.2的10002端口, 远程连接外网192.168.1.3的22端口, 通过两层10.0.0.2, 172.32.0.2跳转到192.168.1.3
autossh -M 0 -o "ExitOnForwardFailure yes" -o "ServerAliveInterval 30" -o "ServerAliveCountMax 3" -fNL 0.0.0.0:10002:192.168.1.3:22 -J root@root@10.0.0.2 root@172.32.0.2
}
function stop(){
for i in `ps aux|grep "\-NL"|grep -v grep|awk '{print $2}'`
do
kill -9 $i
done
}
function ls(){
for i in `ps aux|grep autossh|grep -v grep|grep -v ls|awk '{print $24}'|awk -F ':' '{print $2}'`
do
grep -B 1 $i /script/ssh-tunnel
done
}
case $1 in
"start")
start
;;
"restart")
stop
start
;;
"stop")
stop
;;
"ls")
ls
;;
*) echo "start|restart|stop|ls"
;;
esac