基于Python編寫一個IP地址存活檢查器
更新時間:2024年11月05日 08:45:39 作者:蝸牛其實也很努力
這篇文章主要為大家詳細介紹了如何基于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()
# 創(chuàng)建主窗口
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")
# 運行主循環(huán)
root.mainloop()安裝pyinstaller

制作exe

同級目錄dist下會生成程序 ,運行效果如下

到此這篇關于基于Python編寫一個IP地址存活檢查器的文章就介紹到這了,更多相關Python IP地址存活檢查器內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Django批量查詢優(yōu)化的多種實現(xiàn)方案
在 Django 中處理大規(guī)模數(shù)據(jù)集時,批量查詢是提升性能的關鍵技術,以下是完整的批量查詢實現(xiàn)方案,涵蓋從基礎到高級的各種場景,需要的朋友可以參考下2025-07-07
Pytorch使用卷積神經網(wǎng)絡對CIFAR10圖片進行分類方式
這篇文章主要介紹了Pytorch使用卷積神經網(wǎng)絡對CIFAR10圖片進行分類方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-02-02
將Python腳本通過Wooey轉化為Web應用的簡易解決方案
Wooey 是一個開源的 Python 項目,旨在幫助開發(fā)者快速將 Python 腳本轉化為用戶友好的 Web 應用程序,在本文中,我們將詳細介紹 Wooey 的功能、安裝與配置方法,并展示如何將一個 Python 腳本通過 Wooey 轉化為 Web 應用,需要的朋友可以參考下2025-05-05

