shell脚本检查是否存在tun0虚拟网卡,若不不存在服务器更改port,并重启服务器,客户端修改port,并重新启动客户端
openvp 客户端 /home 目录下各脚本文件名
[root@jira home]# ls openvpn_server_restart.sh openvpn_tunnel_monitor.sh
openvpn_tunnel_monitor.sh 为死循环脚本来检测 tun0 网卡是否存在,若不存在,对服务器端 openvpn server 进行操作,更换port并重启openvpn 服务,同时更改openvpn 客户端port端口对应服务器port端口,同时重新启动客户端
cat openvpn_tunnel_monitor.sh while [ 1 ] do tun0_route=`ifconfig|grep -ci "tun0"` if [ $tun0_route -eq 0 ];then echo "openvpn tunnel is down ,need do the restart operation." >> /tmp/openvpn_tunnel.log ssh root@47*****27 'bash -x -s' < /home/openvpn_server_restart.sh scp root@47******27:/etc/openvpn/server.conf /home server_port=`cat /home/server.conf|grep -i "port"|grep -v "^#"|awk '{print $2}'` sed -i "s@remote.*@remote 47*******27 $server_port@" /etc/openvpn/fanqiang001.conf PID=`ps -fe|grep fangqiang001|grep -v grep|awk '{print $2}'` if [ "$PID" ];then ps -fe|grep fangqiang001|grep -v grep|awk '{print $2}'|xargs kill -9 echo "old openvpn client process is killed" >> /tmp/openvpn_tunnel.log fi source /etc/profile cd /etc/openvpn nohup /usr/sbin/openvpn --cd /etc/openvpn --config fanqiang001.conf --log-append /var/log/openvpn.log >> nohup.out 2>&1 & sleep 5 new_pid=`ps -fe|grep openvpn|grep -v grep|awk '{print $2}'` echo $new_pid if [ "$new_pid" ];then echo " openvpn client process started success !" >> /tmp/openvpn_tunnel.log fi fi sleep 600 done
openvpn_server_restart.sh 脚本主要重新启动openvpn server端
#!/bin/bash server_port=`cat /etc/openvpn/server.conf|grep -i "port"|grep -v "^#"|awk '{print $2}'` server_port=$((server_port+1)) sed -i "s@port.*@port $server_port@" /etc/openvpn/server.conf service openvpn restart
配置后台运行脚本
sh openvpn_tunnel_monitor.sh & > /dev/null 2>&1