本文目录导读:

是的,可以编写实用脚本批量执行 ICMP Ping 检测,以下是几种常见脚本方式:
Windows 批处理脚本
@echo off
echo 批量ICMP检测开始...
for %%i in (192.168.1.1 192.168.1.2 192.168.1.10 8.8.8.8) do (
ping -n 2 %%i | find "TTL" >nul
if errorlevel 1 (
echo %%i - 无法访问
) else (
echo %%i - 正常
)
)
echo 检测结束
pause
读取IP列表文件版本 (iplist.txt):
@echo off
echo 批量ICMP检测开始...
for /f %%i in (iplist.txt) do (
ping -n 1 %%i | find "TTL" >nul
if errorlevel 1 (
echo [FAIL] %%i
) else (
echo [OK] %%i
)
)
pause
Linux Bash 脚本
#!/bin/bash
# 批量Ping脚本
# 方法1: 数组方式
IP_LIST=("192.168.1.1" "192.168.1.2" "8.8.8.8" "baidu.com")
for ip in "${IP_LIST[@]}"; do
if ping -c 2 -W 2 $ip &>/dev/null; then
echo "[OK] $ip - 可达"
else
echo "[FAIL] $ip - 不可达"
fi
done
# 方法2: 读取文件
while read ip; do
if [[ -n "$ip" && ! "$ip" =~ ^# ]]; then
ping -c 1 -W 1 $ip &>/dev/null
if [ $? -eq 0 ]; then
echo "[+] $ip 在线"
else
echo "[-] $ip 离线"
fi
fi
done < ip_list.txt
Python 脚本 (最灵活)
#!/usr/bin/env python3
import subprocess
import platform
import concurrent.futures
import ipaddress
def ping_host(host):
"""Ping单个主机"""
param = '-n' if platform.system().lower() == 'windows' else '-c'
command = ['ping', param, '1', '-W', '1', host]
try:
result = subprocess.run(command,
capture_output=True,
timeout=3,
text=True)
if result.returncode == 0:
return (host, True, "在线")
else:
return (host, False, "离线")
except subprocess.TimeoutExpired:
return (host, False, "超时")
except Exception as e:
return (host, False, f"错误: {e}")
def batch_ping(ip_list):
"""批量并发Ping"""
results = []
with concurrent.futures.ThreadPoolExecutor(max_workers=20) as executor:
future_to_ip = {executor.submit(ping_host, ip): ip for ip in ip_list}
for future in concurrent.futures.as_completed(future_to_ip):
results.append(future.result())
# 结果排序
results.sort(key=lambda x: x[0])
return results
# 使用示例
if __name__ == "__main__":
# 方式1: IP列表
targets = [
"8.8.8.8",
"1.1.1.1",
"192.168.1.1",
"google.com"
]
# 方式2: 生成网段
network = ipaddress.ip_network("192.168.1.0/24", strict=False)
targets = [str(ip) for ip in network.hosts()[:10]] # 只取前10个
# 运行批量检测
print(f"正在检测 {len(targets)} 个主机...")
results = batch_ping(targets)
# 输出结果
for ip, status, msg in results:
status_icon = "✓" if status else "✗"
print(f"{status_icon} {ip}: {msg}")
# 统计
online = sum(1 for _, s, _ in results if s)
print(f"\n汇总: 在线 {online}/{len(results)} 个")
增强版 Python 脚本 (带统计功能)
#!/usr/bin/env python3
import subprocess
import platform
import concurrent.futures
import time
from datetime import datetime
class PingMonitor:
def __init__(self):
self.system = platform.system().lower()
self.results = []
def ping(self, host, count=2):
"""执行Ping并返回详细信息"""
param = '-n' if self.system == 'windows' else '-c'
timeout = '-W' if self.system != 'windows' else '-w'
command = ['ping', param, str(count), timeout, '2', host]
try:
start = time.time()
result = subprocess.run(command,
capture_output=True,
timeout=5,
text=True)
elapsed = time.time() - start
# 解析延迟
latency = None
if result.returncode == 0:
for line in result.stdout.split('\n'):
if 'time=' in line.lower() or '时间=' in line:
# 提取延迟值
import re
match = re.search(r'时间[=<]\s*(\d+\.?\d*)\s*ms', line.lower())
if not match:
match = re.search(r'time[=<]\s*(\d+\.?\d*)\s*ms', line.lower())
if match:
latency = float(match.group(1))
break
return {
'host': host,
'success': result.returncode == 0,
'latency': latency,
'time': elapsed
}
except Exception as e:
return {
'host': host,
'success': False,
'latency': None,
'error': str(e)
}
def batch_ping(self, hosts, max_workers=50):
"""批量并发Ping"""
self.results = []
with concurrent.futures.ThreadPoolExecutor(max_workers=max_workers) as executor:
futures = {executor.submit(self.ping, host): host for host in hosts}
for future in concurrent.futures.as_completed(futures):
self.results.append(future.result())
return self.results
def report(self):
"""生成报告"""
online = [r for r in self.results if r['success']]
offline = [r for r in self.results if not r['success']]
avg_latency = 0
if online:
latencies = [r['latency'] for r in online if r['latency']]
avg_latency = sum(latencies) / len(latencies) if latencies else 0
report = f"""
=== Ping 批量检测报告 ===
时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}
总数: {len(self.results)}
在线: {len(online)} ({len(online)*100//len(self.results)}%)
离线: {len(offline)} ({len(offline)*100//len(self.results)}%)
平均延迟: {avg_latency:.1f}ms
在线列表:
"""
for r in online:
latency = f"{r['latency']}ms" if r['latency'] else "N/A"
report += f" ✓ {r['host']} - {latency}\n"
if offline:
report += "\n离线列表:\n"
for r in offline:
error = r.get('error', '无响应')
report += f" ✗ {r['host']} - {error}\n"
return report
# 使用示例
if __name__ == "__main__":
monitor = PingMonitor()
# 测试目标
test_hosts = [
"8.8.8.8",
"1.1.1.1",
"192.168.1.1",
"baidu.com",
"github.com",
"192.168.1.100" # 可能离线
]
print("开始批量Ping检测...")
monitor.batch_ping(test_hosts)
print(monitor.report())
注意事项
- 权限: Linux下可能需要root权限才能ping某些主机
- 频率: 建议设置合理的并发数和间隔,避免被误判为攻击
- 格式: 确保IP列表文件中每行一个IP地址
- 跨平台: Windows用
-n,Linux用-c控制ping次数
这些脚本可以直接复制使用,按需修改IP列表即可实现批量ICMP检测。