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

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()

  • 11
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值