项目需要,写下这段脚本
通过subprocess.Popen调用系统的ping.exe,获得ping结果文本,再通过正则表达式从结果文本中提取需要的参数。需要考虑中文和英文两种返回结果。
通过这个简单的程序,静下心来学习了Python的正则表达式,了解了re.match, re.search, re.findall之间的不同。以前总是懵懵懂懂一知半解地乱用,觉得自己还是太浮躁了。
戒骄戒躁!!!
def getPING(domain):
''' 调用系统自带的ping.exe实现PING domain,返回值为:ip,丢包率,最短,最长,平均'''
p = subprocess.Popen(["ping.exe", domain], stdin = subprocess.PIPE, stdout = subprocess.PIPE, stderr = subprocess.PIPE, shell = True)
out = p.stdout.read().decode('gbk')
regIP = r'\[\d+\.\d+\.\d+\.\d+\]' ## Pinging www.a.shifen.com [115.239.211.112] with 32 bytes of data
regLost = r'\(\d+%' ## Packets: Sent = 4, Received = 4, Lost = 0 (0% loss) 数据包: 已发送 = 4,已接收 = 4,丢失 = 0 (0% 丢失),
regMinimum = u'Minimum = \d+ms|最短 = \d+ms' ## Minimum = 37ms, Maximum = 38ms, Average = 37ms 最短 = 37ms,最长 = 77ms,平均 = 48ms
regMaximum = u'Maximum = \d+ms|最长 = \d+ms'
regAverage = u'Average = \d+ms|平均 = \d+ms'
ip = re.search(regIP, out)
lost = re.search(regLost, out)
minimum = re.search(regMinimum, out)
maximum = re.search(regMaximum, out)
average = re.search(regAverage, out)
if ip:
ip = ip.group()[1:-1]
if lost:
lost = lost.group()[1:]
if minimum:
minimum = filter(lambda x:x.isdigit(),minimum.group())
if maximum:
maximum = filter(lambda x:x.isdigit(),maximum.group())
if average:
average = filter(lambda x:x.isdigit(),average.group())
return (ip,lost,minimum,maximum,average)