持续检查 VPN 连接 - Python

Bha*_*nan 2 python

当 VPN 断开连接时,是否有任何有效的方法可以在日志文件或控制台上进行检查和报告?

import time
print time.asctime( time.localtime(time.time()) )
Run Code Online (Sandbox Code Playgroud)

可以打印时间,但我不知道递归查找 VPN 是否处于活动状态的代码是什么。稍后(1)对其进行 ping 操作来检查连接是否处于活动状态是一种愚蠢的方法。有什么办法可以实现这个目标吗?

Fer*_*ran 5

这个解决方案依赖于系统,我知道它可以在 Linux 上工作,因为我已经做了类似的事情,但不确定 Windows 上是否有效。我不知道你是否想要一个不涉及 ping 的解决方案,但我认为这是一个很好的解决方案。

import logging, os, time

PING_HOST='10.10.10.10'  # 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
Run Code Online (Sandbox Code Playgroud)

0这是有效的,因为 ping 返回成功的返回码。所有其他返回代码都表示错误。