2
\$\begingroup\$

We need to tunnel certain applications over a VPN at work. Ideally we would use a dedicated firewall/network appliance for this but the only permanent infrastructure we have are Mac Pro's running Squid.

This means that if our VPN connection drops or anything happens to the link, we have to manually click "Connect VPN" and then update squid.conf to point to the new VPN IP. I decided to write an AppleScript task that runs as a cronjob, then depending on whether a disconnect had occurred, squid would then be reconfigured.

AutoReconnectVPN.scpt (AppleScript)

global gAttempts

tell application "System Events"
    tell current location of network preferences
        repeat 10 times
            set myConnection to the service "VPN"
            if myConnection is not null then
                if current configuration of myConnection is not connected then
                    connect myConnection
                    set gAttempts to gAttempts + 1
                else
                    -- Return 0 if theres no need to reconfigure squid
                    return gAttempts
                end if
            end if
            delay 5
            end
    end tell
end tell

SetProxyIP.sh (bash script)

#!/bin/bash

# Sets tcp_outgoing_address in squid.conf to point to IP of ppp0
# Ensure tcp_outgoing_address already exists in squid.conf!

export VPNIP=''
CONFDIR=~/Library/Preferences/squid.conf

for i in 1 2 3 4 5; do
        export VPNIP="$(ifconfig ppp0 | sed -En 's/127.0.0.1//;s/.*inet (addr:)?(([0-9]*\.){3}[0-9]*).*/\2/p')"
        echo "GETTING VPN IP" $VPNIP
        if [[ $VPNIP =~ ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$ ]];
        then
                sed -i .bak 's/.*tcp_outgoing_address.*.*/tcp_outgoing_address '$VPNIP'/' $CONFDIR
                # Would have used squid -k reconfigure, fails with error in our environment?
                kill -9 `cat /tmp/squid.pid` || :
                /usr/local/squid/sbin/squid -f $CONFDIR

                break
        fi
        sleep 1
done

Then a cronjob to run every minute

*/1 * * * * osascript ~/vpnscripts/AutoReconnectVPN.scpt; if [ "$?" -eq "0" ] ; then ~/vpnscripts/SetProxyIP.sh; fi

Perhaps a continual daemon process would be more elegant and remove the possible 1 minute downtime between checks, but this is acceptable for our purposes.

This is my first experience with sed so I'm expecting there could be room for improvement there. My main hope is that someone could stumble upon this and find it useful.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.