python判断网络是否通

2023-11-07

提供两种方法:

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, ":")


本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

python判断网络是否通 的相关文章

随机推荐

  • ElasticSearch高可用安装部署(Linux)

    ElasticSearch高可用安装部署 一 小型的ElasticSearch集群的节点角色规划 对于Ingest节点 如果我们没有格式转换 类型转换等需求 直接设置为false 3 5个节点属于轻量级集群 要保证主节点个数满足 节点数 2
  • log4j2 安装interactsh

    漏洞测试log4j2 sudo apt install gccgo go sudo apt install golang go go env w GOPROXY https goproxy cn direct 1 root kali hom
  • jwt安全问题

    文章目录 jwt安全问题 jwt简介 jwt组成 header payload signature 潜在漏洞 空加密算法 web346 密钥爆破 web348 敏感信息泄露 web349 修改算法RS256为HS256 web350 jwt
  • pytorch cycleGAN代码学习1

    一 新的东西 p s 很多架构都和之前一样 就举些不同的 1 ReplayBuffer Buffers of previously generated samples fake A buffer ReplayBuffer fake B bu
  • JSONException异常

    下面是net sf json JSONException java lang reflect InvocationTargetException异常 net sf json JSONException java lang reflect I
  • 筛选图片,写JSON文件和复制

    筛选图片 写JSON文件和复制 筛选图片 写JSON文件 筛选图片复制 筛选图片 写JSON文件 coding utf 8 from PIL import Image ImageDraw ImageFont import os import
  • NVIDIA Video Codec SDK学习

    这是sdk官网 https developer nvidia com nvidia video codec sdk https docs nvidia com video technologies video codec sdk 这是cud
  • python用于计算和数据处理的包有哪些_数据处理常用Python包

    原博文 2020 05 16 21 07 数据计算 numpy https github com AI 10 Data processing blob master E6 95 B0 E6 8D AE E5 88 86 E6 9E 90 E
  • Django---------创建、运行

    目录 1 安装django 2 pycharm 专业版 创建项目 3 默认项目的文件介绍 4 App的创建和说明 5 启动运行django 1 确保app已注册 settings py 2 编写URL和视图函数对应关系 url py 3 编
  • File类的常用方法

    import java io File import java io IOException public class Demo public static void main String args File file new File
  • xfce4汉化

    xfce4 设置中文 安装locales并配置 sudo apt install locales sudo dpkg reconfigure locales 选择语言编码en US UTF8 zh CN GB2312 zh CN GBK G
  • netty实现websocket发送文本和二进制数据

    最近在学习netty相关的知识 看到netty可以实现 websoket 因此记录一下在netty中实现websocket的步骤 主要实现传递文本消息和传递二进制消息 此处只考虑是图片 如果是别的消息可以考虑使用自定义协议 需求 1 使用
  • centos7最小化安装之后配置网络(ip)

    1 执行命令cd etc sysconfig network scripts 2 找到ifcfg eno16777736类似的文件 3 vi ifcfg eno16777736 4 将ONBOOT no 改为 ONBOOT yes 5 重启
  • 将jar包安装到本地仓库

    首先要安装maven 配置环境变量 百度 so easy 然后打开终端 执行以下命令 注意 红色对用红色 黄色对应黄色 绿色对应绿色 mvn install install file DgroupId cn vicky reddwarf D
  • B站数据分析岗实习生面试记录

    step1 自我介绍一下 还是需要准备以下的 不然一下子介绍自己的话 没话说 而且介绍自己不完全 step2 一道sql的笔试题目 建议刷一下题目呀 一定要刷题 掌握那些最基本的语法 step3 面试题目1 比如对B站近30天的弹幕发送量进
  • Office project 2021安装

    哈喽 大家好 今天一起学习的是project 2021的安装 Microsoft Office project项目管理工具软件 凝集了许多成熟的项目管理现代理论和方法 可以帮助项目管理者实现时间 资源 成本计划 控制 有兴趣的小伙伴也可以来
  • VALSE 文档图像智能报告整理

    目录 引言 端到端检测识别 探索检测和识别的协同作用 减少对标注的依赖 去除一些不必要的组件 文字擦除和编辑 文字辅助场景理解 视频文字擦除和文档矫正 文字识别 自监督预训练 对比学习 更高效的语言模型 手写数学公式识别 文档图像理解 视频
  • java创建数据库连接和对数据库操作的主要步骤

    Java创建数据库连接和对数据库操作的主要五个步骤如下 1 加载数据库驱动 使用 Class forName 方法加载指定的数据库驱动类 例如加载MySQL的驱动类 Class forName com mysql jdbc Driver 2
  • 基于LINUX策略路由的实现

    一 网络结构eth0 10 43 128 10 gw 10 43 0 254 gt interneleth1 61 144 64 106 gw 61 144 64 1 gt interneleth2 192 168 0 2 gw 192 1
  • python判断网络是否通

    提供两种方法 netstats py coding gbk import myarp import os class netStatus def internet on self ip 192 168 150 1 os system arp