Skip to content

Instantly share code, notes, and snippets.

@jneight
Last active August 23, 2019 10:06
Show Gist options
  • Save jneight/8b365b11769f7664e84533e36489bf00 to your computer and use it in GitHub Desktop.
Save jneight/8b365b11769f7664e84533e36489bf00 to your computer and use it in GitHub Desktop.
check ipsec VPN status and get it up if it is down
#!/usr/bin/python3
import re
import os
import subprocess
import logging
from systemd.journal import JournalHandler
logger = logging.getLogger('check_vpn')
logger.addHandler(JournalHandler())
logger.setLevel(logging.INFO)
def get_vpn_names(path):
with open(path, 'r') as f:
return re.findall(r'conn ([\w]+)', f.read())
def check_vpn(vpn_name):
result = subprocess.check_output(['ipsec', 'status', vpn_name])
if b'ESTABLISHED' in result and b'INSTALLED, TUNNEL' in result:
return True
return False
def up_vpn(vpn_name):
result = subprocess.check_output(['ipsec', 'up', vpn_name])
if 'connection \'{}\' established successfully'.format(vpn_name).encode() in result:
return True
return False
if __name__ == '__main__':
vpns_to_check = get_vpn_names('/etc/ipsec.conf')
for vpn in vpns_to_check:
if not check_vpn(vpn):
logger.info('VPN: %s is down, going to reconnect...', vpn)
result = up_vpn(vpn)
if result:
logger.info('VPN: %s is now up', vpn)
else:
logger.info('VPN: %s cannot reconnect', vpn)
else:
logger.info('VPN: %s is up, nice!', vpn)
[Unit]
Description=Check ipsec VPN status
[Service]
Type=simple
ExecStart=/usr/local/bin/check-vpn.py
[Install]
WantedBy=multi-user.target
[Unit]
Description=Call check-vpn.service periodically
[Timer]
OnBootSec=2min
OnUnitActiveSec=5min
[Install]
WantedBy=timers.target
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment