对互联网进行Ping检查连接性

时间:2018-08-15 16:36:29

标签: python-3.x

在尝试找到检查有效Internet连接的最简单方法时,我发现了这一点:

os.system("ping google.com")

但是,我似乎无法使用它。无论我如何处理,它似乎永远循环运行。

输出:

  

PING google.com(172.217.6.206)56(84)字节数据。来自64个字节   lga25s54-in-f206.1e100.net(172.217.6.206):icmp_seq = 1 ttl = 55   来自lga25s54-in-f206.1e100.net(172.217.6.206)的时间= 61.8 ms 64字节:   icmp_seq = 2 ttl = 55 time = 61.7 ms 64字节来自   lga25s54-in-f206.1e100.net(172.217.6.206):icmp_seq = 3 ttl = 55   来自lga25s54-in-f206.1e100.net的时间= 61.9 ms 64字节

     

--- google.com ping统计信息---已发送7个数据包,已接收7个数据包,0%数据包丢失,时间6009ms rtt min / avg / max / mdev =   61.666 / 61.784 / 61.910 / 0.203毫秒

所以我的问题是我如何才能以某种逻辑使用这一行?换句话说,我如何在这方面(或类似的东西)使用它:

if os.system("ping google.com") == (some condition):
    some logic

1 个答案:

答案 0 :(得分:1)

如果您只想检查互联网连接,那么我想这应该符合您的目的

import requests

def check_internet_connection(url='http://www.google.com/', timeout=1):
    try:
        response = requests.get(url, timeout=timeout)
        return True
    except requests.ConnectionError:

        return False

print(check_internet_connection())

编辑:

这可以使用 popen

检查是否存在连接
import os
a = os.popen('ping -c 1 google.com').read()
if a:
    print('Internet connection working')
else:
    print('Internet connection Error')