给ping命令加时间戳并生成带日期的日志文件

  • ping 命令加时间戳

    对网络通路进行监测可使用ping命令,当需要24小时甚至更长时间的持续测试时,记录每一次ping包状态的时间信息就非常有必要,可在网络出现问题时,根据日志来定位问题发生时段。分别验证了windows/linux平台下的操作,涉及字符拼接、powershell 日期函数等技巧。

Linux下给ping命令加时间戳

#!/bin/bash
ethname=eno1
check_dn() {
    while true
    do
         dn="127.0.0.1"
         for IP in $dn; do
         		#注意包含ip地址一行的前缀子串匹配
                #ipaddr=`ifconfig $ethname | awk '/inet addr/ {print $2}' | cut -f2 -d ":"`
                ipaddr=`ifconfig $ethname | awk '/inet / {print $2}' | cut -f2 -d ":"`
                if ping -c 1 $IP >/dev/null; then
                     echo "$(date +"%Y-%m-%d %H:%M:%S"):""  $ipaddr --> $IP Ping success."
                     continue
                fi
                echo "$(date +"%Y-%m-%d %H:%M:%S"):""    $ipaddr --> $IP Ping failure!"
                ifconfig $ethname
         done
         sleep 1
    done
}

#check_dn
check_dn | while read pong; do echo "$pong"; done | tee -a ping-$(date +"%Y-%m-%d-%H:%M: %S").log  

windows下ping命令加时间戳

windows下使用get-date获取时间 并进行格式化,对ping结果加时间戳信息,并且对输出的文件名加时间信息,可用以下命令。以下使用了windows下字符拼接方法,并使用tostring生成 一个当前日期和日间 的文件名。

#以下命令仅支持powershell 运行
ping 127.0.0.1  | Foreach{"{0}-{1}" -f (get-date),$_} > ( 'ping_' + (Get-Date -format "yyyy-MM-dd-HH-MM-ss").ToString()  + '.log' )

The End.


  • 13
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

月光技术杂谈

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值