-
支持 IPv4 / IPv6 自动判断;
-
根据操作系统选择合适的
ping命令格式; -
使用多线程加速存活检测;
-
使用
tqdm显示进度条; -
支持从文件中加载 IP 列表,检测后将存活 IP 保存到输出文件
代码如下:
# -*- coding: utf-8 -*-
import os
import platform
import concurrent.futures
from tqdm import tqdm
# 判断 IP 地址是否为 IPv6
def is_ipv6(ip):
return ":" in ip
# 根据操作系统构建适当的 ping 命令
def ping_ip(ip):
system_name = platform.system().lower() # 获取当前操作系统
count_flag = "-n" if system_name == "windows" else "-c" # ping 次数标志
timeout_flag = "-w" if system_name == "windows" else "-W" # 超时标志
# 构造不同平台下的 IPv4/IPv6 ping 命令
if is_ipv6(ip):
# IPv6 地址处理
if system_name == "windows":
ping_cmd = f"ping -6 {count_flag} 1 {timeout_flag} 2 {ip}"
else:
ping_cmd = f"ping6 {count_flag} 1 {timeout_flag} 2 {ip}"
else:
# IPv4 地址处理
ping_cmd = f"ping {count_flag} 1 {timeout_flag} 2 {ip}"
# 执行 ping 命令,返回 True 表示 IP 存活
return os.system(ping_cmd) == 0
# 从指定文件加载 IP 地址列表
def load_ips(file_path):
try:
with open(file_path, "r", encoding="utf-8") as f:
return [line.strip() for line in f if line.strip()]
except FileNotFoundError:
print(f"[!] 文件 {file_path} 不存在")
return []
# 将存活的 IP 写入到输出文件
def save_alive_ips(alive_ips, output_file):
with open(output_file, "w", encoding="utf-8") as f:
for ip in alive_ips:
f.write(ip + "\n")
# 多线程检测 IP 存活
def detect_alive_ips(ip_list, max_workers=100):
alive_ips = []
# 使用线程池并发检测 IP 存活
with concurrent.futures.ThreadPoolExecutor(max_workers=max_workers) as executor:
futures = {executor.submit(ping_ip, ip): ip for ip in ip_list}
with tqdm(total=len(futures), desc="正在检测 IP 存活", dynamic_ncols=True) as pbar:
for future in concurrent.futures.as_completed(futures):
ip = futures[future]
try:
if future.result(): # ping 成功
alive_ips.append(ip)
except Exception as e:
print(f"[!] IP {ip} 检测异常: {e}")
pbar.update(1)
return alive_ips
# 主程序入口
if __name__ == "__main__":
ip_file = "scan_day/ip.txt" # 输入文件路径
output_file = "alive_ips.txt" # 存活 IP 输出文件
# 加载 IP 列表
ip_list = load_ips(ip_file)
if not ip_list:
exit()
# 并发检测 IP 存活
alive_ips = detect_alive_ips(ip_list)
# 保存检测到的存活 IP
save_alive_ips(alive_ips, output_file)
print(f"\n✅ 存活 IP 共 {len(alive_ips)} 个,已保存到 {output_file}")