1. 程式人生 > >python獲取PING結果

python獲取PING結果

roc odi col def address bsp stdin -1 max

 1 # -*- coding: utf-8 -*-
 2 
 3 import subprocess
 4 import re
 5 
 6 def get_ping_result(ip_address):
 7     p = subprocess.Popen(["ping.exe", ip_address], stdin = subprocess.PIPE, stdout = subprocess.PIPE, stderr = subprocess.PIPE, shell = True)
 8     out = p.stdout.read().decode(gbk)
 9     
10
reg_receive = 已接收 = \d 11 match_receive = re.search(reg_receive, out) 12 13 receive_count = -1 14 15 if match_receive: 16 receive_count = int(match_receive.group()[6:]) 17 18 if receive_count > 0: #接受到的反饋大於0,表示網絡通 19 reg_min_time = 最短 = \d+ms
20 reg_max_time = 最長 = \d+ms 21 reg_avg_time = 平均 = \d+ms 22 23 match_min_time = re.search(reg_min_time, out) 24 min_time = int(match_min_time.group()[5:-2]) 25 26 match_max_time = re.search(reg_max_time, out) 27 max_time = int(match_max_time.group()[5:-2])
28 29 match_avg_time = re.search(reg_avg_time, out) 30 avg_time = int(match_avg_time.group()[5:-2]) 31 32 return [receive_count, min_time, max_time, avg_time] 33 else: 34 print(網絡不通,目標服務器不可達!) 35 return [0, 9999, 9999, 9999] 36 37 if __name__ == __main__: 38 ping_result = get_ping_result(114.80.83.69) 39 print(ping_result)

python獲取PING結果