I have been solving following issue – sometimes my OpenVPN client on Linux machine stopped working and auto-heal feature of OpenVPN was not working properly. So I wanted to set-up a service which will restart service when some host (in this case private IP of OpenVPN server) become unreachable. But you can use my script in more scenarios.
#!/usr/bin/env python3 # /usr/local/sbin/restart_SERVICENAME.py import os,time def reachable(): for i in range(0,3): time.sleep(60) if os.system('ping -c1 HOST_OR_IP 2>&1 > /dev/null') == 0: print('ping succesfull') return True print('host unreachable') return False while(True): if reachable(): continue print('restarting openvpn') os.system('systemctl restart SERVICE_NAME')
# /etc/systemd/system/restart_SERVICENAME.service [Unit] Description=SERVICENAME restart After=network-online.target [Service] Restart=on-failure ExecStart=/usr/local/sbin/restart_SERVICENAME.py [Install] WantedBy=multi-user.target
Do not forget to start and enable this service via systemctl command. Enjoy!