繁体   English   中英

通过Python检测特定接口的互联网

[英]Detecting internet for a specific interface over Python

我正在寻找一种解决方案,以检查特定接口(eth0,wlan0等)是否具有Internet。

我的情况如下。 我有2个活跃的连接。 一个不带Internet的以太网连接(eth0)和一个不带Internet的无线连接(wlan0)。 双方都从各自的DHCP服务器获得了L​​AN IP。

我得出了结论,但我很愿意提出建议,即最佳解决方案将是:

发出ping命令:

ping -I wlan0 -c 3 www.google.com

并让Python接收或接收我是否能够到达目的地(检查:“目标主机不可达”)

import subprocess

command = ["ping", "-I", "wlan0", "-c", "3", "www.google.com"]
find = "Destination Host Unreachable"
p = subprocess.Popen(command, stdout=subprocess.PIPE)
text = p.stdout.read()
retcode = p.wait()

if find in command:
        print "text found"
else:
        print "not found"

但是,这不能产生最佳结果,我真的可以使用一些帮助。

谢谢!

text变量将打印出品脱命令输出,只是在print命令输出中查找文本无效。

是的,因为您没有捕获stderr,所以可以将stderr重定向到stdout,也可以只调用communication以等待过程完成并获取输出:

p = subprocess.Popen(command, stdout=subprocess.PIPE,
                     stderr=subprocess.STDOUT)
out,_ = p.communicate()

您也可以只使用check_call,这将为任何非零退出状态引发错误:

from subprocess import check_call, CalledProcessError, PIPE 

def is_reachable(inter, i, add):
    command = ["ping", "-I", inter, "-c", i, add]
    try:
        check_call(command, stdout=PIPE)
        return True
    except CalledProcessError as e:
        print e.message
        return False

如果只想捕获某个错误,可以检查返回码。

def is_reachable(inter, i, add):
    command = ["ping", "-I", inter, "-c", i, add]
    try:
        check_call(command, stdout=PIPE)
        return True
    except CalledProcessError as e:
        if e.returncode == 1:
            return False
        raise

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM