Skip to content

Instantly share code, notes, and snippets.

@muniu
Forked from winhamwr/ipsec-monitor.sh
Created June 14, 2018 07:15
Show Gist options
  • Save muniu/20a47482b7540ad878d60e29c63f5ffc to your computer and use it in GitHub Desktop.
Save muniu/20a47482b7540ad878d60e29c63f5ffc to your computer and use it in GitHub Desktop.

Revisions

  1. @winhamwr winhamwr created this gist Dec 10, 2013.
    60 changes: 60 additions & 0 deletions ipsec-monitor.sh
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,60 @@
    #!/bin/bash

    function main()
    {
    monitor_from_file $*
    }

    function monitor_vpn_ip_port()
    {
    local CONN_NAME=$1
    local IP=$2
    local PORT=$3

    nc -w 10 -z $IP $PORT || ( \
    echo "$IP $PORT did not respond, resetting connection $CONN_NAME"; \
    ipsec auto --refresh $CONN_NAME;)
    }

    function monitor_from_file()
    {
    local FILE=$1
    if [[ ! -e $FILE ]]; then
    echo "Can not find file $FILE."
    return 1
    fi

    # load the file into memory. Hope it's not too big. :)
    # -t strips out the newlines on each line.
    mapfile -t MYARRAY < $FILE
    # init local variable to contain the current connection name.
    local CONN=
    for LINE in "${MYARRAY[@]}"; do
    # Skip over any lines that have the comment at the very beginning.
    if [[ $LINE =~ ^\# ]]; then continue

    # Look for a line that looks like this which defines a VPN connection:
    # conn CONNECTION-NAME
    elif [[ $LINE =~ ^conn[\ ] ]]; then
    # extract the part after the "conn " to get the name.
    CONN=`echo $LINE | sed 's/^conn //'`

    # Look for a line where we have the commented 'monitor' keyword.
    # Example: #monitor 172.17.105.80 9898
    elif [[ $LINE =~ \#monitor ]]; then
    # Remove everything from the beginning up to and including the "#monitor "
    IP_PORT=`echo $LINE | sed 's/^.*#monitor //'`
    printf "`date` monitoring $CONN \t $IP_PORT\n"
    # IP_PORT should be space delimited and hence should work as separate parameters.
    monitor_vpn_ip_port $CONN $IP_PORT

    # if we have a blank line, that ends any connection configuration.
    elif [[ $LINE =~ ^$ ]]; then
    CONN=
    fi
    done
    }


    # now start running the script by calling main() with all parameters.
    main $*