领导离职,刚好公司网络管理小哥有需要脚本测试的需求,小哥为人诚恳,很谦虚,值得交朋友,于是写了一个给他。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#!/bin/bash

# 检查参数数量
if [ "$#" -ne 2 ]; then
echo "Usage: $0 <ip_file_path> <ping_delay_threshold>"
exit 1
fi

IP_FILE=$1
DELAY_THRESHOLD=$2
LOG_FILE="ping_results_${DELAY_THRESHOLD}ms.log"
THREADS=10

# 清空日志文件
> $LOG_FILE

# 定义ping函数
ping_ip() {
local ip=$1
local delay_threshold=$2
local result
local delay
local status
local datetime
local output=""

for i in {1..5}; do
if [[ "$OSTYPE" == "darwin"* ]]; then
result=$(ping -c 1 -W 1000 $ip 2>&1)
else
result=$(ping -c 1 -W 1 $ip 2>&1)
fi

datetime=$(date '+%Y-%m-%d %H:%M:%S')

if [[ $? -ne 0 ]]; then
status="TIMEOUT"
output+="$datetime $ip $status\n"
else
delay=$(awk -F'time=' '/time=/{print $2+0}' <<< "$result")
if (( $(awk "BEGIN {print ($delay > $delay_threshold)}") )); then
status="EXCEEDED"
output+="$datetime $ip $delay ms $status\n"
fi
fi
done

if [[ -n "$output" ]]; then
echo -e "$output" >> $LOG_FILE
fi
}

export -f ping_ip
export LOG_FILE
export DELAY_THRESHOLD

# 使用xargs和&实现多线程
cat $IP_FILE | xargs -n 1 -P $THREADS -I {} bash -c 'ping_ip "{}" '"$DELAY_THRESHOLD"

echo "Ping completed. Results are in $LOG_FILE"

使用说明

  1. 将上述脚本保存为 ping_script.sh
  2. 给予脚本执行权限:
    1
    chmod +x ping_script.sh
  3. 运行脚本,并提供两个参数:IP文件路径和ping延迟上限:
    1
    ./ping_script.sh /mnt/data/ips(1).txt 100
    其中 /mnt/data/ips(1).txt 是IP文本文件的路径,100 是ping的延迟上限(单位:毫秒)。

脚本说明

  • 日志文件名:日志文件名动态生成,包含用户输入的延迟上限参数,格式为 ping_results_<DELAY_THRESHOLD>ms.log
  • ping_ip函数:针对 macOS 和 Linux 的 ping 命令选项有所不同。macOS 使用 -W 1000(单位是毫秒),而 Linux 使用 -W 1(单位是秒)。
  • 统一输出格式:对于每个IP地址,累计5次ping的结果,然后一次性打印到日志文件中。如果延时不超过上限,则不打印结果。记录的格式为:时间 IP 延迟时间/状态。
  • 多线程执行:使用 xargs 实现多线程操作。-P $THREADS 参数指定并发线程数,-n 1 参数指定每次处理一个IP。