Skip to content

Instantly share code, notes, and snippets.

@tiancheng91
Created August 28, 2025 09:32
Show Gist options
  • Save tiancheng91/266463dc60c138bafd945c67efa1d9b2 to your computer and use it in GitHub Desktop.
Save tiancheng91/266463dc60c138bafd945c67efa1d9b2 to your computer and use it in GitHub Desktop.
断流检查
#!/bin/bash
# 检查参数是否为空
if [ $# -eq 0 ]; then
echo "用法: $0 <目标地址>"
echo "示例: $0 8.8.8.8"
echo " $0 www.example.com"
echo "功能: 持续ping指定目标,按Ctrl+C显示统计结果"
exit 1
fi
TARGET=$1
# 初始化计数器
total_packets=0
timeout_packets=0
# 定义中断处理函数
cleanup() {
echo -e "\n===== 测试结果 ====="
echo "目标地址: $TARGET"
echo "累计请求次数: $total_packets"
echo "超时次数: $timeout_packets"
# 计算错误比例
if [ $total_packets -gt 0 ]; then
error_rate=$(echo "scale=2; $timeout_packets / $total_packets * 100" | bc)
echo "错误比例: $error_rate%"
else
echo "错误比例: 0%"
fi
exit 0
}
# 捕获SIGINT信号(ctrl+c)
trap cleanup SIGINT
# 提示信息
echo "开始网络断流测试,按Ctrl+C结束..."
echo "目标地址: $TARGET"
echo "----------------------------------------"
# 持续ping测试
while true; do
# 发送一个ping包,超时时间为2秒
ping -c 1 -W 2 $TARGET > /dev/null 2>&1
# 检查ping命令的退出状态
if [ $? -ne 0 ]; then
echo "$(date '+%Y-%m-%d %H:%M:%S') - 超时"
((timeout_packets++))
else
echo "$(date '+%Y-%m-%d %H:%M:%S') - 正常"
fi
((total_packets++))
# 每秒钟发送一个ping包
sleep 1
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment