在内网机器上执行下面的命令
ssh -p22 -f -N -R 0.0.0.0:2222:localhost:22 [email protected]
-p22
用于指定外网机器的 sshd 端口2222
是指定开放内网机器的端口(可随机定义)22
是内网机器的 sshd 端口root
是外网机器的用户127.0.0.1
是外网机器的 ip
现在就可以在外网机器上执行下面的命令即可登录到内网机器
ssh -p2222 root@localhost
root
是内网机器的用户
为了防止连接断开,编写一个脚本在 crontab 中执行
crontab 每分钟执行一次 auto_remote.sh
*/1 * * * * bash /root/auto_remote.sh >>/dev/null 2>&1
auto_remote.sh
#/bin/bash
user=root
ip=*.*.*.* # 改成你的外网 IP
port=23111
cport=`echo $((RANDOM%5000+5000))`
mport=22
cmd="ssh -p$port -f -N -R $cport:localhost:$mport $user@$ip"
reg="ssh -p$port -f -N -R [0-9]\{4\}:localhost:$mport $user@$ip"
isrun=`ps -ef | grep "$reg" | grep -v grep`
if [ "$isrun"x == "x" ]; then
echo "notrun"
$cmd
echo "$cmd"
else
echo "isrun"
echo "$isrun"
fi