How to restart linux service when icmp / ping unreachable (OpenVPN tip)

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.

Python script

#!/usr/bin/env python3
# /usr/local/sbin/
import os,time
def reachable():
    for i in range(0,3):
        if os.system('ping -c1 HOST_OR_IP 2>&1 > /dev/null') == 0:
            print('ping succesfull')
            return True
        print('host unreachable')
    return False

    if reachable():
    print('restarting openvpn')
    os.system('systemctl restart SERVICE_NAME')

SystemD file

# /etc/systemd/system/restart_SERVICENAME.service
Description=SERVICENAME restart

Last steps

Do not forget to start and enable this service via systemctl command. Enjoy!