Python ping3和多线程threading获取网络环境中设备在线IP地址。需要ping测试的地址为多个段,将多段地址写在txt中

本文介绍了一个Python脚本,用于对IP范围进行ping测试,包括处理CIDR表示法和单个IPv4地址。使用线程池提高速度,同时记录成功和失败的IP地址。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、在ranges中可以写多段地址比如10.1.1.0/23,换行10.2.2.0/24
2、默认情况下脚本/24的地址段,默认不会ping .254的地址,如果有多个网段,或者跨网段了。就会ping .254的地址。
3、在测试代码的时候,发现代码运行ping的速度过快,ping通的地址和实际地址是有差异的。这个版本的速度还行,不会出现数据错误
import ping3
import ipaddress
from concurrent.futures import ThreadPoolExecutor
from datetime import datetime


def ping_ip(ip):
    try:
        if ping3.ping(str(ip), timeout=1):
            return ip
    except Exception as e:
        print(f"Error pinging {ip}: {e}")


def main():
    try:
        now = datetime.now().strftime("%Y%m%d_%H%M%S")
        success_filename = f"ping_successes_{now}.txt"
        fail_filename = f"ping_fails_{now}.txt"

        with open("ip_ranges.txt", "r") as ip_ranges_file:
            ip_ranges = [line.strip() for line in ip_ranges_file if line.strip()]

        success_ips = []
        with ThreadPoolExecutor(max_workers=10) as executor:
            futures = []
            for ip_range in ip_ranges:
                if "/" in ip_range:  # 检查是否是CIDR表示法
                    # 如果是CIDR表示法,则直接处理IPv4Network
                    for ip in ipaddress.IPv4Network(ip_range):
                        futures.append(executor.submit(ping_ip, ip))
                else:
                    # 否则,处理单个IPv4地址
                    futures.append(executor.submit(ping_ip, ipaddress.IPv4Address(ip_range)))

            for future in futures:
                result = future.result()
                if result is not None:
                    success_ips.append(result)

        # 将成功的 IP 地址写入文件
        with open(success_filename, "w") as success_file:
            for ip in success_ips:
                success_file.write(str(ip) + "\n")

        print(f"Ping scan complete. Successful pings written to {success_filename}, fails written to {fail_filename}")

    except FileNotFoundError:
        print("Error: ip_ranges.txt file not found.")
    except Exception as e:
        print(f"An error occurred: {e}")


if __name__ == "__main__":
    main()

为了解决局域网内设备在线状态检测及获取IPMac地址的需求,你可以利用Python的Win32API库来访问系统底层功能,实现高效且稳定的信息采集。以下步骤代码片将指导你完成这一过程: 参考资源链接:[Python脚本:一键提取局域网在线IP与Mac地址多线程检测](https://wenku.csdn.net/doc/7memmpffiz?spm=1055.2569.3001.10343) 首先,使用`arp -a`命令获取局域网中所有设备的ARP缓存信息。此步骤可以使用`subprocess`模块来执行系统命令,并捕获输出结果。 ```python import subprocess def get_arp_cache(): result = subprocess.run(['arp', '-a'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True) arp_output = result.stdout.split('\\n') return arp_output ``` 其次,解析`arp_output`以提取IPMac地址。你可能需要正则表达式来匹配输出中的模式,提取出相关的地址信息。 ```python import re def parse_arp_info(arp_output): arp_info = [] for line in arp_output: match = re.search(r'(\d+\.\d+\.\d+\.\d+)\s+at\s+(\w{2}-\w{2}-\w{2}-\w{2}-\w{2}-\w{2})', line) if match: arp_info.append((match.group(1), match.group(2))) return arp_info ``` 接着,为了实现多线程功能,可以使用`threading`模块。通过创建多个线程,每个线程负责一部分IP地址的检测,从而加快整个检测过程。 ```python import threading def check_ip_online(ip): # 使用ping命令检查IP是否在线 # 此处省略具体实现 pass def thread_ip_online(ip_list): for ip in ip_list: thread = threading.Thread(target=check_ip_online, args=(ip,)) thread.start() ``` 最后,为了将所有信息输出到文本文件中,可以使用Python的文件操作函数`open``write`。 ```python def write_to_file(ip_mac_list, file_name): with open(file_name, 'w') as *** *** ***'{ip}\t{mac}\n') ``` 将以上功能整合到一个脚本中,并在主函数`main`中调用,就可以实现你的需求。记住,在实际应用中还需要考虑异常处理线程同步等问题,确保程序的健壮性。 通过以上步骤,你可以编一个Python脚本来检测局域网内设备在线状态,并获取它们的IPMac地址。此脚本将通过多线程技术提高检测效率,并将结果输出到文本文件中,为网络管理监控提供方便。建议深入研究《Python脚本:一键提取局域网在线IP与Mac地址多线程检测》,这将为你提供更详细的实现指导深入理解网络工具在Python中的应用。 参考资源链接:[Python脚本:一键提取局域网在线IP与Mac地址多线程检测](https://wenku.csdn.net/doc/7memmpffiz?spm=1055.2569.3001.10343)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值