持续检查VPN连接 - Python

2 投票
3 回答
11734 浏览
提问于 2025-04-16 21:53

有没有什么简单有效的方法,可以在日志文件或者控制台上检查并报告VPN断开连接的情况呢?

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

我可以打印出时间,但我不知道怎么写代码去递归检查VPN是否还在连接中。一直用ping命令去检查连接是否活跃,这样做太傻了。有没有其他方法可以做到这一点呢?

3 个回答

0

这个方法使用的是与你的IP地址相关的“连接特定的DNS后缀”的主机名称(通常是公司的VPN):

import os
import platform
def check_ping():
   hostname = "xyz.com" #hostname will be..Name under: "Connection-specific DNS Suffix" when you type "ipconfig" in cmd..
   response = os.system("ping " + ("-n 1 " if  platform.system().lower()=="windows" else "-c 1 ") + hostname)
   # and then check the response...
   if response == 0:
       pingstatus = "Network Active: Connected"
   else:
       pingstatus = "Network Error: Not Connected"

   return pingstatus
response = check_ping()
print(response)
0

如果VPN的IP地址发生变化,你可以检查一下是否已经建立了连接。

import psutil
import logging, os, time
import subprocess
import sys

procname = "yourprocess_name"

while True:
    cmdout = subprocess.Popen(["ifconfig | grep tun"],stdout = subprocess.PIPE, shell=True).communicate()[0]
    print "cmdout: "+str(cmdout)
    time.sleep(2)
    #-----
    if "tun" in cmdout:
        print "seems to be ok"
    if not "tun" in cmdout: 
        # perform action for lost connection
        print "killing "+str(procname)
        for proc in psutil.process_iter():
            # check whether the process name matches
            print "Listing procname: "+str(proc.name())
            if proc.name() == procname:
                proc.kill()
                sys.exit()
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

之所以有效,是因为ping命令成功时会返回一个0的代码。其他的返回代码则表示出错了。

撰写回答