在一个工业互联网项目里,因需要在生产期间,监控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包的间隔。