[Video] v18. Автоматическое восстановление vpn подключения на Raspberry Pi (bash script).

В этом видео я рассказываю о как можно автоматизировать переподключение/восстановление vpn в случае какого-либо сбоя на своём Raspberry Pi или любом другом Linux сервере.
Для мониторинга и переподключения я использую самописный скрипт написанный на bash. Для автоматизации проверки использую cron.

Мой скрипт:

pi@raspberrypi ~ $ cat vpntunneltest/vpntunneltest.sh
#!/bin/bash
#
# declare a,b as integer
# b - minimum amount of lines in the test file.
# This is when vpn is not working because of some reasons.
declare -i a=0
declare -i b=6

# test vpn connectivity
ping 172.20.0.1 -c 10 > /home/pi/vpntunneltest/ping_172.20.0.1-c10.txt

# calculate how many lines test file has, if more than 6 than vpn is working.
a=$(wc -l < /home/pi/vpntunneltest/ping_172.20.0.1-c10.txt) # check vpn - if :a" more than "b" than vpn is working. if [ "$a" -gt "$b" ] then # everything is working fine. No worries. No reason to reset the vpn. echo " " echo "Tunnel is working fine." echo " " exit 0 else # something is wrong and it will be better to reset the vpn. echo " " echo "Something is wrong and it will be better to reset the vpn." echo " " # what is current PID of openvpn process pidofopenvpn=$(pidof openvpn) # kill existing vpn connection, just kill withour '-9' # to let client app tell server to close the session # and do not wait ~2min to close the session. kill $pidofopenvpn # wait for 5 seconds to let openvpn server halt previous session: sleep 5 # In a case of some bug. If normal soft kill command had no results - check if any 'openvpn' process is working and use 'kill -9' pidof openvpn > /home/pi/vpntunneltest/pidof_openvpn.txt
pidofopenvpn=$(pidof openvpn)
# check how many symbols in '/home/pi/vpntunneltest/pidof_openvpn.txt'
pidofopenvpn_length=$(wc -m < /home/pi/vpntunneltest/pidof_openvpn.txt) if [ "$pidofopenvpn_length" -gt 1 ] then # something is wrong, try to use 'kill -9' # echo 'Not all processes have been stopped, trying 'kill -9'' # echo 'Current pidof of openvpn processes:' # cat /home/pi/vpntunneltest/pidof_openvpn.txt kill -9 $pidofopenvpn # wait for 180 seconds to let openvpn server kill previous session (avoid hold timer expiration...): sleep 180 # start a new vpn connection /usr/sbin/openvpn --config /home/pi/client.ovpn else # start a new vpn connection /usr/sbin/openvpn --config /home/pi/client.ovpn fi fi exit 0