openvpn_connect.sh 连接,内网拨号上网,断网续联

2024-02-28 23:38:08 浏览数 (3)

代码语言:shell复制
#!/bin/bash
# auto connect vpn . get internal network connection  [inˈ tər nl  in tor no 内部]

ip=10.1.1.1
#ip=10.1.1.9
VPNfile=/datadisk/eisc/vpn/home/homeserver1.ovpn
sudo chmod 777 $VPNfile

debList=(
openvpn
)

download_deb(){

   for i in ${debList[*]}
   do
      debname=`echo $i | awk -F"_" '{print $1}'`
      debnameInstalled=`sudo dpkg -l | grep -w  "$debname" | awk -F" " '{print $2}' `
      debnameInstalledLength=${#debnameInstalled}

      if [ $debnameInstalledLength -gt 1 ]
      then
         echo "[ok] 该包 $i 已经安装,安装信息: $debnameInstalled"
      else
         echo "[runing] 正在检查是否下载安装包: $i"
         if [ ! -e $i ]
         then
            echo "[runing] 当前没有下载,正在下载包:$i"
            case "$i" in
               "openvpn")    sudo apt-get install openvpn    ;;
               *) echo "该包没有定义下载地址,包: $i"
            esac
         else
            echo  "[ok] 已经安装: $i "
         fi

      fi
   done
}




connect()
{
    echo "正在检测拨号上网状态.....  "

    ping -c1 -W1 $ip   | grep from
    if [ $? != 0 ]
    then
        failFlag=1
        echo "[fail]  Connection failed.       i=$i   failCount=$failCount  failFlag=$failFlag"
    else
        failFlag=0

        failCount=0                 # 网络连接上一次为通畅,重新开始计数
        FailMaxCount=0;

        failFlag=0
        FailMaxFlag=0
        echo "[ok] connection is successful.   i=$i   failCount=$failCount  failFlag=$failFlag"
        sleep 1
    fi

    # 将ping -c 2  ping 两次; -i 每次间隔; -w 总共等待时间;  vpn 连接上后需要等待一些时间
    # $? 是上一个程序执行是否成功的标志,如果执行成功则$? 为0,否则 不为0

    if [ "$failCount" -gt "5" ]
    then
        FailMaxFlag=1
        i=0;
        failCount=0;                # 大于 5 重置次数,重新计数 
        echo "[reset] i=0; failCount=0; failFlag=0  ; outValue  i=$i failCount=$failCount  failFlag=$failFlag FailMaxFlag=$FailMaxFlag "
        sleep 1;
    else
        FailMaxFlag=0;
    fi


    if [ "$FailMaxCount" -gt "1" ]  # 5次错误的倍数 0 1 两次, 
    then
        sudo killall openvpn ; sudo openvpn $VPNfile > /dev/null & 
        failFlag=0;
        echo "Network reconnection... "
        sleep 12                            # openvpn 连接需要时间,连接成功后再进行检测网络通讯
    fi



}


failCount=0
FailMaxCount=0;

failFlag=0
FailMaxFlag=0

i=0;
# 初始化变量

main()
{
    #download_deb
    for((;;))
    do
        connect 
        ((i  ))
        echo "当前尝试次数 : $i 状态: $status"

        if [ "$failFlag" = "1" ] 
        then 
            ((failCount  ))
        fi

        if [ "$FailMaxFlag" = "1" ] 
        then 
            ((FailMaxCount  ))
        fi

        if [ $i > 999 ]
        then
            i=0;
        fi

    done
}
main


# 小绿叶技术博客一键下载: wget eisc.cn/file/ubuntu/shell/server/openvpn_connect.sh

1 人点赞