判断网络是否通

提供两种方法:

netstats.py

# -*- coding: gbk -*-
import myarp
import os
class netStatus:
    def internet_on(self,ip="192.168.150.1"):
        os.system("arp -d 192.168.150.1")
        if myarp.arp_resolve(ip, 0) == 0:   #使用ARP ping的方法
            return True
        else:
            return False
    def ping_netCheck(self, ip):           #直接ping的方法
        os.system("arp -d 192.168.150.1")
        cmd = "ping "  str(ip)   " -n 2"
        exit_code = os.system(cmd)
        if exit_code:
            return False
        return True
if __name__ == "__main__":
    net = netStatus()
    print net.ping_netCheck("192.168.150.2")

myarp.py(这个是从ARP模块改来的) 

"""
ARP / RARP module (version 1.0 rev 9/24/2011) for Python 2.7
Copyright (c) 2011 Andreas Urbanski.
Contact the me via e-mail: urbanski.andreas@gmail.com
This module is a collection of functions to send out ARP (or RARP) queries
and replies, resolve physical addresses associated with specific ips and
to convert mac and ip addresses to different representation formats. It
also allows you to send out raw ethernet frames of your preferred protocol
type. DESIGNED FOR USE ON WINDOWS.
NOTE: Some functions in this module use winpcap for windows. Please make
sure that wpcap.dll is present in your system to use them.
LICENSING:
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>
"""
__all__ = ['showhelp', 'find_device', 'open_device', 'close_device', 'send_raw',
           'multisend_raw', 'arp_resolve', 'arp_reply', 'rarp_reply', 'mac_straddr',
           'ip_straddr', 'ARP_REQUEST', 'ARP_REPLY', 'RARP_REQUEST', 'RARP_REPLY',
           'FRAME_SAMPLE']
""" Set this to True you wish to see warning messages """
__warnings__ = False
from ctypes import *
import socket
import struct
import time
FRAME_SAMPLE = """
Sample ARP frame
 ----------------- ------------------------ 
| Destination MAC | Source MAC             |
 ----------------- ------------------------ 
| \\x08\\x06 (arp)  | \\x00\\x01  (ethernet)   |
 ----------------- ------------------------ 
| \\x08\\x00 (internet protocol)             |
 ------------------------------------------ 
| \\x06\\x04 (hardware size & protocol size) |
 ------------------------------------------ 
| \\x00\\x02 (type: arp reply)               | 
 ------------ ----------- ----------------- 
| Source MAC | Source IP | Destination MAC |
 ------------ --- ------- ----------------- 
| Destination IP | ... Frame Length: 42 ...
 ---------------- 
"""
""" Frame header bytes """
ARP_REQUEST = "\x08\x06\x00\x01\x08\x00\x06\x04\x00\x01"
ARP_REPLY = "\x08\x06\x00\x01\x08\x00\x06\x04\x00\x02"
RARP_REQUEST = "\x80\x35\x00\x01\x08\x00\x06\x04\x00\x03"
RARP_REPLY = "\x80\x35\x00\x01\x08\x00\x06\x04\x00\x04"
""" Defines """
ARP_LENGTH = 42
RARP_LENGTH = 42
DEFAULT = 0
""" Look for wpcap.dll """
try:
    wpcap = cdll.wpcap
except WindowsError:
    print "Error loading wpcap.dll! Ensure that winpcap is properly installed."
""" Loading Windows system libraries should not be a problem """
try:
    iphlpapi = windll.Iphlpapi
    ws2_32 = windll.ws2_32
except WindowsError:
    """ Should it still fail """
    print "Error loading windows system libraries!"
""" Import functions """
if wpcap:
    """ Looks up for devices """
    pcap_lookupdev = wpcap.pcap_lookupdev
    """ Opens a device instance """
    popen_live = wpcap.pcap_open_live
    """ Sends raw ethernet frames """
    pcap_sendpacket = wpcap.pcap_sendpacket
    """ Close and cleanup """
    pcap_close = wpcap.pcap_close
""" Find the first device available for use. If this fails
to retrieve the preferred network interface identifier,
disable all other interfaces and it should work."""
def find_device():
    errbuf = create_string_buffer(256)
    device = c_void_p
    device = pcap_lookupdev(errbuf)
    return device
""" Get the handle to a network device. """
def open_device(device=DEFAULT):
    errbuf = create_string_buffer(256)
    if device == DEFAULT:
        device = find_device()
    """ Get a handle to the ethernet device """
    eth = popen_live(device, 4096, 1, 1000, errbuf)
    return eth
""" Close the device handle """
def close_device(device):
    pcap_close(device)
""" Send a raw ethernet frame """
def send_raw(device, packet):
    if not pcap_sendpacket(device, packet, len(packet)):
        return len(packet)
""" Send a list of packets at the specified interval """
def multisend_raw(device, packets=[], interval=0):
    """ Bytes sent """
    sent = 0
    for p in packets:
        sent  = len(p)
        send_raw(device, p)
        time.sleep(interval)
    """ Return the number of bytes sent"""
    return sent
""" Resolve the mac address associated with the
destination ip address"""
def arp_resolve(destination, strformat=True, source=None):
    mac_addr = (c_ulong * 2)()
    addr_len = c_ulong(6)
    dest_ip = ws2_32.inet_addr(destination)
    if not source:
        src_ip = ws2_32.inet_addr(socket.gethostbyname(socket.gethostname()))
    else:
        src_ip = ws2_32.inet_addr(source)
    """
    Iphlpapi SendARP prototype
    DWORD SendARP(
      __in     IPAddr DestIP,
      __in     IPAddr SrcIP,
      __out    PULONG pMacAddr,
      __inout  PULONG PhyAddrLen
    );
    """
    error = iphlpapi.SendARP(dest_ip, src_ip, byref(mac_addr), byref(addr_len))
    return error
""" Send a (gratuitous) ARP reply """
def arp_reply(dest_ip, dest_mac, src_ip, src_mac):
    """ Test input formats """
    if dest_ip.find('.') != -1:
        dest_ip = ip_straddr(dest_ip)
    if src_ip.find('.') != -1:
        src_ip = ip_straddr(src_ip)
    """ Craft the arp packet """
    arp_packet = dest_mac   src_mac   ARP_REPLY   src_mac   src_ip   \
                 dest_mac   dest_ip
    if len(arp_packet) != ARP_LENGTH:
        return -1
    return send_raw(open_device(), arp_packet)
""" Include RARP for consistency :)"""
def rarp_reply(dest_ip, dest_mac, src_ip, src_mac):
    """ Test input formats """
    if dest_ip.find('.') != -1:
        dest_ip = ip_straddr(dest_ip)
    if src_ip.find('.') != -1:
        src_ip = ip_straddr(src_ip)
    """ Craft the rarp packet """
    rarp_packet = dest_mac   src_mac   RARP_REPLY   src_mac   src_ip   \
                  src_mac   src_ip
    if len(rarp_packet) != RARP_LENGTH:
        return -1
    return send_raw(open_device(), rarp_packet)
""" Convert c_ulong*2 to a hexadecimal string or a printable ascii
string delimited by the 3rd parameter"""
def mac_straddr(mac, printable=False, delimiter=None):
    """ Expect a list of length 2 returned by arp_query """
    if len(mac) != 2:
        return -1
    if printable:
        if delimiter:
            m = ""
            for c in mac_straddr(mac):
                m  = "x" % ord(c)   delimiter
            return m.rstrip(delimiter)
        return repr(mac_straddr(mac)).strip("\'")
    return struct.pack("L", mac[0])   struct.pack("H", mac[1])
""" Convert address in an ip dotted decimal format to a hexadecimal
string """
def ip_straddr(ip, printable=False):
    ip_l = ip.split(".")
    if len(ip_l) != 4:
        return -1
    if printable:
        return repr(ip_straddr(ip)).strip("\'")
    return struct.pack(
        "BBBB",
        int(ip_l[0]),
        int(ip_l[1]),
        int(ip_l[2]),
        int(ip_l[3])
    )
def showhelp():
    helpmsg = """ARP MODULE HELP (Press ENTER for more or CTRL-C to break)
Constants:
    Graphical representation of an ARP frame
    FRAME_SAMPLE
    Headers for crafting ARP / RARP packets
    ARP_REQUEST, ARP_REPLY, RARP_REQUEST, RARP_REPLY
    Other
    ARP_LENGTH, RARP_LENGTH, DEFAULT
Functions:
    find_device() - Returns an identifier to the first available network
    interface.
    open_device(device=DEFAULT) - Returns a handle to an available network
    device.
    close_device() - Close the previously opened handle.
    send_raw(device, packet) - Send a raw ethernet frame. Returns
    the number of bytes sent.
    multisend_raw(device, packetlist=[], interval=0) - Send multiple packets
    across a network at the specified interval. Returns the number of bytes
    sent.
    arp_resolve(destination, strformat=True, source=None) - Returns the mac
    address associated with the ip specified by 'destination'. The destination
    ip is supplied in dotted decimal string format. strformat parameter
    specifies whether the return value is in a hexadecimal string format or
    in list format (c_ulong*2) which can further be formatted using
    the 'mac_straddr' function (see below). 'source' specifies the ip address
    of the sender, also supplied in dotted decimal string format.
    arp_reply(dest_ip, dest_mac, src_ip, src_mac) - Send gratuitous ARP
    replies. This can be used for ARP spoofing if the parameters are chosen
    correctly. dest_ip is the destination ip in either dotted decimal
    string format or hexadecimal string format (returned by 'ip_straddr').
    dest_mac is the destination mac address and must be in hexadecimal
    string format. If 'arp_resolve' is used with strformat=True the return
    value can be used directly. src_ip specifies the ip address of the
    sender and src_mac the mac address of the sender.
    rarp_reply(dest_ip, dest_mac, src_ip, src_mac) - Send gratuitous RARP
    replies. Operates similar to 'arp_reply'.
    mac_straddr(mac, printable=False, delimiter=None) - Convert a mac
    address in list format (c_ulong*2) to normal hexadecimal string
    format or printable format. Alternatively a delimiter can be specified
    for printable formats, e.g ':' for ff:ff:ff:ff:ff:ff.
    ip_straddr(ip, printable=False) - Convert an ip address in
    dotted decimal string format to hexadecimal string format. Alternatively
    this function can output a printable representation of the hex
    string format.
"""
    for line in helpmsg.split('\n'):
        print line,
        raw_input('')
if __name__ == "__main__":
    """ Test the module by sending an ARP query """
    ip = "10.0.0.8"
    result = arp_resolve(ip, 0)
    print ip, "is at", mac_straddr(result, 1, ":")

检测网络连接状态的几种方式

第一种

import socket
ipaddress = socket.gethostbyname(socket.gethostname())
if ipaddress == '127.0.0.1':
    return False
else:
    return True

缺点:如果IP是静态配置,无法使用,因为就算断网,返回的也是配置的静态IP

第二种

import urllib3
try:
    http = urllib3.PoolManager()
    http.request('GET', 'https://baidu.com')
    return True
except as e:
    return False

第三种

import os
ret = os.system("ping baidu.com -n 1")
return True if res == 0 else False

第四种

import subprocess
import os 
ret = subprocess.run("ping baidu.com -n 1", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
return True if ret.returncode == 200 else False

以上为个人经验,希望能给大家一个参考,也希望大家多多支持Devmax。

python如何判断网络是否通的更多相关文章

  1. XCode 3.2 Ruby和Python模板

    在xcode3.2下,我的ObjectiveCPython/Ruby项目仍然可以打开更新和编译,但是你无法创建新项目.鉴于xcode3.2中缺少ruby和python的所有痕迹(即创建项目并添加新的ruby/python文件),是否有一种简单的方法可以再次安装模板?我发现了一些关于将它们复制到某个文件夹的信息,但我似乎无法让它工作,我怀疑文件夹的位置已经改变为3.2.解决方法3.2中的应用程序模板

  2. Swift基本使用-函数和闭包(三)

    声明函数和其他脚本语言有相似的地方,比较明显的地方是声明函数的关键字swift也出现了Python中的组元,可以通过一个组元返回多个值。传递可变参数,函数以数组的形式获取参数swift中函数可以嵌套,被嵌套的函数可以访问外部函数的变量。可以通过函数的潜逃来重构过长或者太复杂的函数。

  3. 10 个Python中Pip的使用技巧分享

    众所周知,pip 可以安装、更新、卸载 Python 的第三方库,非常方便。本文小编为大家总结了Python中Pip的使用技巧,需要的可以参考一下

  4. Swift、Go、Julia与R能否挑战 Python 的王者地位

    本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容,请发送邮件至dio@foxmail.com举报,一经查实,本站将立刻删除。

  5. 红薯因 Swift 重写开源中国失败,貌似欲改用 Python

    本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容,请发送邮件至dio@foxmail.com举报,一经查实,本站将立刻删除。

  6. 你没看错:Swift可以直接调用Python函数库

    上周Perfect又推出了新一轮服务器端Swift增强函数库:Perfect-Python。对,你没看错,在服务器端Swift其实可以轻松从其他语种的函数库中直接拿来调用,不需要修改任何内容。以如下python脚本为例:Perfect-Python可以用下列方法封装并调用以上函数,您所需要注意的仅仅是其函数名称以及参数。

  7. Swift中的列表解析

    在Swift中完成这个的最简单的方法是什么?我在寻找类似的东西:从Swift2.x开始,有一些与你的Python样式列表解析相当的东西。(在这个意义上,它更像是Python的xrange。如果你想保持集合懒惰一路通过,只是这样说:与Python中的列表解析语法不同,Swift中的这些操作遵循与其他操作相同的语法。

  8. swift抛出终端的python错误

    每当我尝试启动与python相关的swift时,我都会收到错误.我该如何解决?

  9. 在Android上用Java嵌入Python

    解决方法看看this,它适用于J2SE,你可以尝试在Android上运行.

  10. 在android studio中使用python代码构建android应用程序

    我有一些python代码和它的机器人,我正在寻找一种方法来使用android项目中的那些python代码.有没有办法做到这一点!?解决方法有两种主要工具可供使用,它们彼此不同:>QPython>Kivy使用Kivy,大致相同的代码也可以部署到IOS.

随机推荐

  1. 10 个Python中Pip的使用技巧分享

    众所周知,pip 可以安装、更新、卸载 Python 的第三方库,非常方便。本文小编为大家总结了Python中Pip的使用技巧,需要的可以参考一下

  2. python数学建模之三大模型与十大常用算法详情

    这篇文章主要介绍了python数学建模之三大模型与十大常用算法详情,文章围绕主题展开详细的内容介绍,具有一定的参考价值,感想取得小伙伴可以参考一下

  3. Python爬取奶茶店数据分析哪家最好喝以及性价比

    这篇文章主要介绍了用Python告诉你奶茶哪家最好喝性价比最高,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习吧

  4. 使用pyinstaller打包.exe文件的详细教程

    PyInstaller是一个跨平台的Python应用打包工具,能够把 Python 脚本及其所在的 Python 解释器打包成可执行文件,下面这篇文章主要给大家介绍了关于使用pyinstaller打包.exe文件的相关资料,需要的朋友可以参考下

  5. 基于Python实现射击小游戏的制作

    这篇文章主要介绍了如何利用Python制作一个自己专属的第一人称射击小游戏,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起动手试一试

  6. Python list append方法之给列表追加元素

    这篇文章主要介绍了Python list append方法如何给列表追加元素,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教

  7. Pytest+Request+Allure+Jenkins实现接口自动化

    这篇文章介绍了Pytest+Request+Allure+Jenkins实现接口自动化的方法,文中通过示例代码介绍的非常详细。对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下

  8. 利用python实现简单的情感分析实例教程

    商品评论挖掘、电影推荐、股市预测……情感分析大有用武之地,下面这篇文章主要给大家介绍了关于利用python实现简单的情感分析的相关资料,文中通过示例代码介绍的非常详细,需要的朋友可以参考下

  9. 利用Python上传日志并监控告警的方法详解

    这篇文章将详细为大家介绍如何通过阿里云日志服务搭建一套通过Python上传日志、配置日志告警的监控服务,感兴趣的小伙伴可以了解一下

  10. Pycharm中运行程序在Python console中执行,不是直接Run问题

    这篇文章主要介绍了Pycharm中运行程序在Python console中执行,不是直接Run问题,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教

返回
顶部