使用 ssh 借助外网机器实现内网穿透实现远程登录

在内网机器上执行下面的命令

ssh -p22 -f -N -R 0.0.0.0:2222:localhost:22 [email protected]

现在就可以在外网机器上执行下面的命令即可登录到内网机器

ssh -p2222 root@localhost

为了防止连接断开,编写一个脚本在 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

点击进入评论 ...