#!/bin/bash # IPsec watchdog # # Installation instructions # 1. Save this script as: /etc/ipsec.d/ipsec-watchdog.sh # 2. Change owner: sudo chown root: /etc/ipsec.d/ipsec-watchdog.sh # 3. Change permissions: sudo chmod a+x /etc/ipsec.d/ipsec-watchdog.sh # # This script should be executed from crontab under root account # # 1. Switch to root account with: sudo -i # 2. Then edit crontab for root: crontab -e # 3. In new line copy and paste (without #): # * * * * * sudo /etc/ipsec.d/ipsec-watchdog.sh >> /var/log/syslog # 4. Save the file and exit # 5. Check the logs if every minute watchdog starts: tail -f /var/log/syslog function _TIMESTAMP () { timestamp=$(date +'%b %d %k:%M:%S') echo $timestamp $(hostname) $0[$$] $* } function _CHECK_TUNNEL () { ping -c 1 -W 3 100.65.0.1 > /dev/null 2>&1 if [ $? -ne 0 ]; then _TIMESTAMP "[ERROR] Tunnel is not working" _RESTART_IPSEC else _TIMESTAMP "[INFO] Tunnel is working and responding" fi } function _RESTART_IPSEC () { ls -l /etc/ipsec.d/*.conf | awk -F '/' '{ print $4 }' | awk -F '.' '{ print $1 }' | while read tunnel; do _TIMESTAMP "[INFO] Restarting IPsec" if ipsec restart; then _TIMESTAMP "[INFO] ipsec restart [DONE]" _TIMESTAMP "[INFO] Waiting 5 sec" && sleep 5 _TIMESTAMP "[INFO] Starting IPsec tunnel $tunnel" if ipsec up $tunnel; then _TIMESTAMP "[INFO] IPsec tunnel $tunnel started [DONE]" else _TIMESTAMP "[ERROR] Unable to start tunnel $tunnel" exit 1 fi else _TIMESTAMP "[ERROR] Unable to restart ipsec" exit 1 fi done } _CHECK_TUNNEL