Project

General

Profile

ipsec-monitor.sh

c b, 22.08.2013 01:47

Download (1.92 KB)

 
1
#!/bin/bash
2

    
3
function main()
4
{
5
    local SLEEP_SECONDS=60
6
    while [[ 0 == 0 ]]; do
7
        monitor_from_file $*
8
        sleep $SLEEP_SECONDS
9
    done
10
}
11

    
12
function monitor_vpn_ip_port()
13
{
14
    local CONN_NAME=$1
15
    local IP=$2
16
    local PORT=$3
17
    
18
    nc -w 10 -z $IP $PORT || ( \
19
        echo "$IP $PORT did not respond, resetting connection $CONN_NAME"; \
20
        ipsec down $CONN_NAME; ipsec up $CONN_NAME; )
21
}
22

    
23
function monitor_from_file()
24
{
25
    local FILE=$1
26
    if [[ ! -e $FILE ]]; then
27
        echo "Can not find file $FILE."
28
        return 1
29
    fi
30

    
31
    # load the file into memory. Hope it's not too big. :)
32
    # -t strips out the newlines on each line.
33
    mapfile -t MYARRAY < $FILE
34
    # init local variable to contain the current connection name.
35
    local CONN=
36
    for LINE in "${MYARRAY[@]}"; do
37
        # Skip over any lines that have the comment at the very beginning.
38
        if [[ $LINE =~ ^\# ]]; then continue
39
        
40
        # Look for a line that looks like this which defines a VPN connection:
41
        # conn CONNECTION-NAME
42
        elif [[ $LINE =~ ^conn[\ ]  ]]; then
43
            # extract the part after the "conn " to get the name.
44
            CONN=`echo $LINE | sed 's/^conn //'`
45

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

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

    
62

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