You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何编写批量Ping多个IP地址并将连通成功结果写入文件的脚本

批量Ping连通性检测脚本实现方案

以下提供三种主流环境的实现方式,可根据自身使用场景选择:

1. Linux/macOS 环境 Bash 脚本实现

适用于类Unix系统,无需额外依赖:

#!/bin/bash
# 待检测IP列表文件路径
IP_LIST="./ip_list.txt"
# 存活IP输出文件路径
OUTPUT_FILE="./success_ip.txt"
# 清空原有输出文件
> "$OUTPUT_FILE"

# 逐行读取IP执行检测
while IFS= read -r ip || [[ -n "$ip" ]]; do
    # 跳过空行
    [[ -z "$ip" ]] && continue
    # ping检测:发2个包,超时1秒,屏蔽过程日志
    ping -c 2 -W 1 "$ip" > /dev/null 2>&1
    if [ $? -eq 0 ]; then
        echo "$ip" >> "$OUTPUT_FILE"
        echo "检测到存活IP:$ip"
    fi
done < "$IP_LIST"

echo "检测完成,存活IP已写入 $OUTPUT_FILE"
  • 用法:
    • 将待检测IP逐行写入同目录的ip_list.txt,一行一个IP
    • 给脚本加执行权限:chmod +x ping_check.sh
    • 运行脚本:./ping_check.sh
    • 若IP数量多,可在ping命令后加&实现并发检测,需自行控制并发数避免系统资源占用过高

2. Windows 环境 PowerShell 脚本实现

适配Windows原生环境,无需额外安装软件:

# 待检测IP列表路径
$ipList = ".\ip_list.txt"
# 存活IP输出路径
$outputFile = ".\success_ip.txt"

# 清空原有输出
if (Test-Path $outputFile) {
    Clear-Content $outputFile
}

Get-Content $ipList | ForEach-Object {
    $ip = $_.Trim()
    if ([string]::IsNullOrEmpty($ip)) {
        return
    }
    # ping检测:发2个包,超时1秒
    if (Test-Connection -ComputerName $ip -Count 2 -TimeoutSeconds 1 -Quiet -ErrorAction SilentlyContinue) {
        Add-Content -Path $outputFile -Value $ip
        Write-Host "检测到存活IP:$ip"
    }
}

Write-Host "检测完成,存活IP已写入 $outputFile"
  • 用法:
    • 将待检测IP逐行写入同目录的ip_list.txt
    • 在脚本所在目录右键选择「在此处打开PowerShell窗口」,执行.\ping_check.ps1即可

3. 跨平台Python脚本实现

全系统通用,只要环境安装了Python3即可运行:

import os
import platform
from pathlib import Path

def ping_check(ip: str) -> bool:
    # 适配不同系统的ping命令参数
    count_param = '-n' if platform.system().lower() == 'windows' else '-c'
    timeout_param = '-w' if platform.system().lower() == 'windows' else '-W'
    timeout_val = '1000' if platform.system().lower() == 'windows' else '1'
    command = f"ping {count_param} 2 {timeout_param} {timeout_val} {ip}"
    # 屏蔽执行日志
    null_target = " > nul 2>&1" if platform.system().lower() == 'windows' else " > /dev/null 2>&1"
    return os.system(command + null_target) == 0

if __name__ == "__main__":
    ip_list_path = Path("./ip_list.txt")
    output_path = Path("./success_ip.txt")
    
    # 初始化输出文件
    with open(output_path, 'w', encoding='utf-8') as f:
        pass
    
    # 读取待检测IP列表
    with open(ip_list_path, 'r', encoding='utf-8') as f:
        ip_list = [line.strip() for line in f if line.strip()]
    
    for ip in ip_list:
        if ping_check(ip):
            print(f"检测到存活IP:{ip}")
            with open(output_path, 'a', encoding='utf-8') as f:
                f.write(f"{ip}\n")
    
    print(f"检测完成,存活IP已写入 {output_path.resolve()}")
  • 用法:
    • 将待检测IP逐行写入同目录的ip_list.txt
    • 执行脚本:python ping_check.py
    • 若需要提升检测速度,可引入concurrent.futures.ThreadPoolExecutor实现多线程并发检测

内容的提问来源于stack exchange,提问作者WolfHank

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.18 14:09:03