用Python实现ping加时间戳,并生成ping包日志

在一个工业互联网项目里,因需要在生产期间,监控5G CPE的网络时延。用python写了一个简单的脚本,脚本在windows服务器下运行,并在windows里设置定时任务,每天早上7:00启动ping包脚本,一直ping到晚上12点,并按每天的日期生成ping包log,以供需要分析网络情况时查询。

脚本以python编写,代码如下:

#!/usr/bin/python
# -*- coding:gbk -*-

import os
import re
import time
from datetime import datetime
import traceback

UE1 = 'XXXXXXX'
UE1_ip = '192.168.1.100'
ping_date = datetime.now().strftime('%Y%m%d')
log_file = 'E:\PingCpe\\' + UE1 + '-' + ping_date + '.txt'
ping_commad = 'ping ' + UE1_ip + ' -n 1 -l 64'  #注意ping后面的空格

time_condition = 1
while(time_condition):
	nowTime = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
	ping = os.popen(ping_commad).read()
	ping = re.compile(r'来自..+',re.M).findall(ping)
	if ping == []:
		ping_str = "请求超时。"
	else:
		ping_str = ",".join(ping)
	try:
		with open(log_file,'a') as f1:
			f1.write(str(nowTime) + '  ping ' + truck + '  ' + ping_str + '\n')
	except:
		print('Writing log_file error!')
		traceback.print_exc()
			
	now_Time = nowTime.split(' ')
	now_Time_date = now_Time[0].replace('-','')
	now_Time_time = now_Time[1].replace(':','')
	if(now_Time_date == ping_date and int(now_Time_time) - 235958 <= 0):  # '235958' 表示时间 23:59:58
		time_condition = 1
	else:
		time_condition = 0	
	#time.sleep(0.5)  #设置sleep时间,调节ping的间隔

上面脚本中,可通过设置 time.sleep( ) 函数的等待时间调节ping包的间隔。 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

hui_farmer

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

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

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

打赏作者

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

抵扣说明:

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

余额充值