Bhavani Kannan Bhavani Kannan - 9 months ago 97
Python Question

Continuous check for VPN Connectivity - Python

Is there any efficient way to check and report in a log file or on the console may be... when ever the VPN is disconnected?

import time
print time.asctime( time.localtime(time.time()) )

Can print the time but I do not know what is the code to recursively find whether the VPN is active or not. Pinging it in a while(1) would be a stupid way to check if the connection is active or not. Any way to achieve this?


This solution is system dependent, I know it works on Linux becaus I've done something similar, but don0't know if it wiorks on Windows. I don't know if you want a solution not involving ping, but I think this is a good solution.

import logging, os, time

PING_HOST=''  # some host on the other side of the VPN

while True:
    retcode = os.system('ping -c 1 %s' % PING_HOST)

    if retcode:  
       # perform action for lost connection
       logging.warn('Lost visibility with %s' % PING_HOST)

    time.sleep(10)  # sleep 10 seconds

This works because ping returns a return code of 0 for success. All other return codes signify an error.