监控网络丢包脚本
#!/bin/bash
TARGET_HOST="127.0.0.1"
while true; do
PING_OUTPUT=$(ping -c 1 -w 2 $TARGET_HOST | awk '{ print $0"\t" strftime("%Y-%m-%d %H:%M:%S",systime()); fflush()}')
# echo "${PING_OUTPUT}"
# 检查ping命令是否成功执行(返回值为0)
if [ $? -ne 0 ]; then
echo "${PING_OUTPUT}"
echo "Ping命令执行失败。"
exit 1
fi
# # 检查输出结果中是否包含"packet loss"并统计丢包情况
PACKET_LOSS=$( echo "${PING_OUTPUT}" | grep -oP '(\d+)% packet loss' | awk '{print $1}' | grep -oP '(\d+)')
if [[ $PACKET_LOSS -gt 0 ]]; then
echo "${PING_OUTPUT}";
echo "Ping失败,存在丢包情况。丢包率:$PACKET_LOSS%。";
exit 1
fi
sleep 1
done