python

关注公众号 jb51net

关闭
首页 > 脚本专栏 > python > Python IP地址存活检查器

基于Python编写一个IP地址存活检查器

作者:蜗牛其实也很努力

这篇文章主要为大家详细介绍了如何基于Python编写一个IP地址存活检查器,文中的示例代码讲解详细,感兴趣的小伙伴可以了解一下

代码

import tkinter as tk
import subprocess
import threading
import ipaddress
from concurrent.futures import ThreadPoolExecutor
import os
 
def ping_ip(ip):
    try:
        ping_command = ["ping", "-c", "1", str(ip)] if os.name != 'nt' else ["ping", "-n", "1", str(ip)]
        output = subprocess.run(ping_command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        if output.returncode == 0:
            return f"{ip} 被占用\n", "occupied"
        else:
            return f"{ip} 未被占用\n", "free"
    except Exception as e:
        return f"检查 {ip} 时出错: {str(e)}\n", None
 
def update_result(result, tag):
    result_text.config(state=tk.NORMAL)
    result_text.insert(tk.END, result, tag)
    result_text.config(state=tk.DISABLED)
 
def check_ip_range(cidr):
    try:
        network = ipaddress.ip_network(cidr)
    except ValueError as e:
        update_result(f"无效的 CIDR: {str(e)}\n", None)
        return
 
    with ThreadPoolExecutor(max_workers=20) as executor:
        future_to_ip = {executor.submit(ping_ip, ip): ip for ip in network.hosts()}
        for future in future_to_ip:
            result, tag = future.result()
            if tag == "occupied":
                update_result(result, "occupied")
            elif tag == "free":
                update_result(result, "free")
            else:
                update_result(result, None)
 
def on_check_button_click():
    cidr = cidr_entry.get()
    threading.Thread(target=check_ip_range, args=(cidr,)).start()
 
# 创建主窗口
root = tk.Tk()
root.title("IP 地址存活检查器")
 
# 输入框
tk.Label(root, text="Example:192.168.1.0/24):").pack(pady=5)
cidr_entry = tk.Entry(root, width=20)
cidr_entry.pack(pady=5)
 
# 检查按钮
check_button = tk.Button(root, text="Check", command=on_check_button_click)
check_button.pack(pady=10)
 
# 结果文本框
result_text = tk.Text(root, width=50, height=20, state=tk.DISABLED)
result_text.pack(pady=10)
 
# 设置文本标签的颜色
result_text.tag_config("occupied", foreground="red")
result_text.tag_config("free", foreground="green")
 
# 运行主循环
root.mainloop()

安装pyinstaller

制作exe

同级目录dist下会生成程序 ,运行效果如下

到此这篇关于基于Python编写一个IP地址存活检查器的文章就介绍到这了,更多相关Python IP地址存活检查器内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文