自动重连虚拟机,端口转发

键盘侠 2021年09月23日 1,449次浏览

windows系统需要安装 git

  • 将打开sh的程序 默认使用git bash打开
  • 需要启用ssh无密码登陆

具体代码

#!/bin/bash
while true
do

    ping 192.168.19.125 -n 2
    u20=$?

    ping 192.168.19.128 -n 2

    u16=$?

    echo "u20 = $u20  u16 = $u16"

    u16SshIsConn=`netstat -ano | grep 3128 | grep LISTEN | awk 'NR==1 {print $4}'`
    u20SshIsConn=`netstat -ano | grep 3125 | grep LISTEN | awk 'NR==1 {print $4}'`

    u16RemoteIsConn=`netstat -ano | grep 5128 | grep LISTEN | awk 'NR==1 {print $4}'`
    u20RemoteIsConn=`netstat -ano | grep 5125 | grep LISTEN | awk 'NR==1 {print $4}'`

    echo "u16Conn = $u16IsConn u20Conn = $u20IsConn"

    if [ $u16 == 0 ]
    then
        if [ "$u16RemoteIsConn" != "LISTENING" ]
        then
            ssh -qNf -L *:3128:192.168.19.128:22 wudl@192.168.19.128
        fi
        if [ "$u16SshIsConn" != "LISTENING" ]
        then
            ssh -qNf -L *:5128:192.168.19.128:3389 wudl@192.168.19.128
        fi

    fi

    if [ $u20 == 0 ]
    then
        if [ "$u20SshIsConn" != "LISTENING" ]
        then
            ssh -qNf -L *:3125:192.168.19.125:22 wudl@192.168.19.125
        fi
        if [ "$u20RemoteIsConn" != "LISTENING" ]
        then
            ssh -qNf -L *:5125:192.168.19.125:3389 wudl@192.168.19.125
        fi
    fi
    sleep 120
done

添加入口后台运行脚本

#!/bin/bash

nohup.exe /c/apps/auto_tunnel.sh &

添加自动运行

运行 win+R 输入 shell:startup 然后将入口脚本添加上去