python如何判断网络是否通

目录
  • 判断网络是否通
  • 检测网络连接状态的几种方式

判断网络是否通

提供两种方法:

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 += "%02x" % 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

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

(0)

相关推荐

  • python 判断网络连通的实现方法

    开发中偶尔需要判断网络的连通性,没有什么方法比 ping 更直接了当,通常检查网络情况都是运行命令ping www.baidu.com ,查看输出信息即可. C:\Users>ping www.baidu.com 正在 Ping www.baidu.com [61.135.169.125] 具有 32 字节的数据: 来自 61.135.169.125 的回复: 字节=32 时间=4ms TTL=57 来自 61.135.169.125 的回复: 字节=32 时间=7ms TTL=57 来自 61

  • python判断设备是否联网的方法

    本文实例为大家分享了python判断设备是否联网的具体代码,供大家参考,具体内容如下 直接上代码,就是用判断socket能不连上的方法来判断. #!/usr/bin/env python # -*- coding: utf-8 -*- import socket def isNetOK(testserver): s=socket.socket() s.settimeout(3) try: status = s.connect_ex(testserver) if status == 0: s.cl

  • Python测试网络连通性示例【基于ping】

    本文实例讲述了Python测试网络连通性.分享给大家供大家参考,具体如下: Python代码 #!/usr/bin/python # -*- coding:GBK -*- """Document: network script, keep network always working, using python3""" import os import time PING_RESULT = 0 NETWORK_RESULT = 0 def Dis

  • python如何判断网络是否通

    目录 判断网络是否通 检测网络连接状态的几种方式 判断网络是否通 提供两种方法: 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,

  • python 实现判断ip连通性的方法总结

    python 以下是个人学习 python 研究判断ip连通性方法的集合. 缺点可能有办法解决,如有错误,欢迎矫正. 方法一 import os return1=os.system('ping -n 2 -w 1 172.21.1.183') print return1 缺点:会弹出cmd 窗口 方法二 #-*- coding: utf-8 -*- import subprocess import re p = subprocess.Popen(["ping.exe ", '172.2

  • Python获取网段内ping通IP的方法

    问题描述 在某些问题背景下,需要确认是否多台终端在线,也就是会使用我们牛逼的ping这个命令,做一些的ping操作,如果需要确认的设备比较少,也还能承受.倘若,在手中维护的设备很多.那么这无疑会变成一个恼人的问题.脚本的作用就凸显了.另外,我们需要使用多线程的一种措施,否则单线程很难在很短的时间内拿到统计结果. 应用背景 有多台设备需要维护,周期短,重复度高; 单台设备配备多个IP,需要经常确认网络是否通常: 等等其他需要确认网络是否畅通的地方 问题解决 使用python自带threading模

  • python 修改本地网络配置的方法

    本文主要说一下怎么使用Python来修改本地的ip和dns等,因为有本地的ip和dns都是随机获取的,有些时候不是很方便,需要修改,我就稍微的封装了一下,但是随机ip和网关.子网掩码等我都没有设置为参数,因为经常用也懒得改了,可以自己去修改一下. 测试的时候,在win8.1上面需要用管理员身份才能执行,win7似乎是不需要管理员身份的. 使用的Python库是WMI,这个是默认安装了的.如果没有去网上下载即可. 该说的都在注释里,就直接上代码了. # -*- coding: utf-8 -*-

  • python数据类型判断type与isinstance的区别实例解析

    在项目中,我们会在每个接口验证客户端传过来的参数类型,如果验证不通过,返回给客户端"参数错误"错误码. 这样做不但便于调试,而且增加健壮性.因为客户端是可以作弊的,不要轻易相信客户端传过来的参数. 验证类型用type函数,非常好用,比如 >>type('foo') == str True >>type(2.3) in (int,float) True 既然有了type()来判断类型,为什么还有isinstance()呢? 一个明显的区别是在判断子类. type(

  • iOS判断网络请求超时的方法

    本文介绍了iOS判断网络请求超时的方法,代码具体如下: + (AFHTTPRequestOperation *)requestOperationWithUrl:(NSString *)url requetMethod:(NSString *)method paramData:(NSDictionary *)aParamData constructingBodyWithBlock:(void (^)(id <AFMultipartFormData> formData))block success

  • python实现从网络下载文件并获得文件大小及类型的方法

    本文实例讲述了python实现从网络下载文件并获得文件大小及类型的方法.分享给大家供大家参考.具体实现方法如下: import urllib2 from settings import COOKIES opener = urllib2.build_opener() cookies = ";".join("%s=%s" % (k, v) for k, v in COOKIES.items()) opener.addheaders.append(('Cookie', c

  • 浅谈Python数据类型判断及列表脚本操作

    数据类型判断 在python(版本3.0以上)使用变量,并进行值比较时.有时候会出现以下错误: TypeError: unorderable types: NoneType() < int() 或者类似的类型错误. 这是因为一方变量的数据类型不明(python无法判断),所以出错. 在一般情况下,可以提前对要使用的变量进行定义并赋值,例如: var=' ' 或者 var=0 等等. 但是,若变量在比较前,是通过调用函数或者其他表达式赋值的,以上方法可能行不通,因为如果调用的函数如果存在错误或者没

  • Python编程判断这天是这一年第几天的方法示例

    本文实例讲述了Python编程判断这天是这一年第几天的方法.分享给大家供大家参考,具体如下: 题目:输入某年某月某日,判断这一天是这一年的第几天? 实现代码: year=int(input('请输入年:')) month=int(input('请输入月:')) day=int(input('请输入天:')) sum=day days = [31,28,31,30,31,30,31,31,30,31,30,31] i=0 if ( year%4 == 0 and year%100 != 0) or

随机推荐