持续ping并显示时间脚本

发布时间 2023-11-16 11:04:18作者: 多喜欢你哟
#!/bin/bash
 
# 设置ping的目标IP地址
target_ip="baidu.com"
 
# 设置文件名和路径
filename="ping.log"
filepath="/"
 
# 创建日志文件
touch "${filepath}${filename}"
 
# 循环进行ping测试并输出每秒的时间并重定向到文件里
while true
do
    now=$(date +"%Y-%m-%d %H:%M:%S")
    ping_result=$(ping -c 1 "${target_ip}" | grep "time=" | awk '{print $4,$5,$7,$8}')
    echo "${now} ${ping_result}" >> "${filepath}${filename}"
    sleep 1
done
 
# 每5个小时分割一次日志文件
while true
do
    now=$(date +"%Y-%m-%d %H:%M:%S")
    if [[ $now == *"00:00:00"* ]]; then
        mv "${filepath}${filename}" "${filepath}${filename}_${now}.log"
        touch "${filepath}${filename}"
    fi
    sleep 60
done