首页 > 代码库 > python获取PING结果

python获取PING结果

 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结果