返回顶部
首页 > 资讯 > 后端开发 > Python >python如何判断网络是否通
  • 349
分享到

python如何判断网络是否通

2024-04-02 19:04:59 349人浏览 独家记忆

Python 官方文档:入门教程 => 点击学习

摘要

目录判断网络是否通检测网络连接状态的几种方式判断网络是否通 提供两种方法: netstats.py # -*- coding: gbk -*- import myarp import

判断网络是否通

提供两种方法:

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

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

--结束END--

本文标题: python如何判断网络是否通

本文链接: https://lsjlt.com/news/118121.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

猜你喜欢
  • python如何判断网络是否通
    目录判断网络是否通检测网络连接状态的几种方式判断网络是否通 提供两种方法: netstats.py # -*- coding: gbk -*- import myarp import...
    99+
    2024-04-02
  • python 判断网络连通
    开发中偶尔需要判断网络的连通性,没有什么方法比 ping 更直接了当,通常检查网络情况都是运行命令ping www.baidu.com ,查看输出信息即可。 C:\Users>ping www.baidu.com 正在 P...
    99+
    2023-01-31
    网络 python
  • nodejs如何判断网络通不通
    这篇文章主要讲解了“nodejs如何判断网络通不通”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“nodejs如何判断网络通不通”吧!使用ping命令检测在Node.js中,可以使用child...
    99+
    2023-07-05
  • nodejs如何判断下载网络文件是否存在
    本篇内容主要讲解“nodejs如何判断下载网络文件是否存在”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“nodejs如何判断下载网络文件是否存在”吧!在Node.js中,下载网络文件是一项非常常...
    99+
    2023-07-05
  • Android判断网络连接是否可用
    ConnectivityManager manager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVI...
    99+
    2022-06-06
    连接 网络连接 Android
  • python ping 判断主机是否连通
    #! /usr/bin/env python import os if(os.system('ping -c 1 -w 1180.23.212.1')==0):   print 'OK' else:   print 'Connection ...
    99+
    2023-01-31
    主机 python ping
  • java如何判断http地址是否连通
    本篇文章为大家展示了java如何判断http地址是否连通,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。 下面代码看下java判断http地址是否连通private boolean...
    99+
    2023-06-22
  • 通过Python判断主机是否存在
    判断对方主机是否存在! import os status = os.system("ping -c 1 www.baidu.com"); if status == 0: print '连接成功!'; else: p...
    99+
    2023-01-31
    是否存在 主机 Python
  • Android编程判断是否连接网络的方法【WiFi及3G判断】
    本文实例讲述了Android编程判断是否连接网络的方法。分享给大家供大家参考,具体如下: 判断wifi网络是否链接: public static boolean isWiFi...
    99+
    2022-06-06
    连接 方法 3g Android
  • Python如何判断数独是否合法
    介绍 该数独可能只填充了部分数字,其中缺少的数字用 . 表示。 注意事项 一个合法的数独(仅部分填充)并不一定是可解的。我们仅需使填充的空格有效即可。 解体思路 将数独按照行、列和块进行预处理,然后分...
    99+
    2022-06-04
    如何判断 是否合法 数独
  • python如何判断是否为字符串
    这篇“python如何判断是否为字符串”除了程序员外大部分人都不太理解,今天小编为了让大家更加理解“python如何判断是否为字符串”,给大家总结了以下内容,具有一定借鉴价值,内容详细步骤清晰,细节处理妥当,希望大家通过这篇文章有所收获,下...
    99+
    2023-06-06
  • python 如何判断字典是否为空?
    在python里,{},[],(),等都等价于False! if dict: print 'not Empty'   ...
    99+
    2023-01-31
    字典 为空 如何判断
  • 如何判断网站是否过度优化
    如何判断网站是否过度优化,针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。一、首页底部是否加入大量无意义的锚链接这一点貌似是国内某一SEO大师...
    99+
    2024-04-02
  • 如何判断一个网站是否有cdn
    在Windows系统中检测网站是否有cdn的方法在Windows系统中使用组合键“win+R”,输入“cmd”,进入DOS窗口;进入DOS窗口后,在窗口中输入“nslookup + 网站域名”,进行查询;最后,在Address栏中查看IP地...
    99+
    2024-04-02
  • java如何判断是否是url
    java使用正则表达式判断是否是url public static boolean isURL(String str){ //转换为小写 str = str.toLowerCase(); ...
    99+
    2017-04-25
    java url
  • Android如何判断是否Root
    这篇文章主要为大家展示了“Android如何判断是否Root”,内容简而易懂,条理清晰,希望能够帮助大家解决疑惑,下面让小编带领大家一起研究并学习一下“Android如何判断是否Root”这篇文章吧。为了照顾那些着急的同学,先直接给出结论:...
    99+
    2023-06-28
  • Android中判断网络是否连接实例详解
    Android中判断网络是否连接实例详解 在android中,如何监测网络的状态呢,这个有的时候也是十分重要的,方法如下: public class ConnectionDe...
    99+
    2022-06-06
    连接 Android
  • python中如何判断路径是否存在
    python中判断路径是否存在的方法:1、在win操作系统中找到python程序目录;2、打开idle工具;3、在idle中新建一个shell脚本;4、输入“import os”指令导入os模块;5、通过“os.path.exists(文件...
    99+
    2024-04-02
  • python如何判断文件夹是否为空
    python中判断文件夹是否为空的方法:在python中可使用“os.path.exists(文件路径)”命令来指定文件夹路径从而判断它是否为空即可。具体操作方法:在win系统的开始菜单中找到python程序。在python程序目录中找到并...
    99+
    2024-04-02
  • 如何判断网站是否受到DDoS攻击
    判断网站是否受到DDoS攻击的方法:1、使用ping命令进行判断,如果发现Ping超时或丢包严重,服务器也访问不了,则可能遭受了流量攻击;2、使用Netstat命令进行判断,如果网站访问突然非常缓慢或无法访问了,但还可以Ping通,则可能遭...
    99+
    2024-04-02
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作