Use python to get sample code for Ping results
- 2020-06-07 04:48:27
- OfStack
preface
This article mainly shares with you about the use of python to obtain Ping results related content, share for your reference and learning, the following words do not say much, let's see a detailed introduction.
Sample code:
# -*- coding: utf-8 -*-
import subprocess
import re
def get_ping_result(ip_address):
p = subprocess.Popen(["ping.exe", ip_address], stdin = subprocess.PIPE, stdout = subprocess.PIPE, stderr = subprocess.PIPE, shell = True)
out = p.stdout.read().decode('gbk')
reg_receive = ' Have received = \d'
match_receive = re.search(reg_receive, out)
receive_count = -1
if match_receive:
receive_count = int(match_receive.group()[6:])
if receive_count > 0: # The feedback is greater than 0 , represents network access
reg_min_time = ' The shortest = \d+ms'
reg_max_time = ' The longest = \d+ms'
reg_avg_time = ' On average, = \d+ms'
match_min_time = re.search(reg_min_time, out)
min_time = int(match_min_time.group()[5:-2])
match_max_time = re.search(reg_max_time, out)
max_time = int(match_max_time.group()[5:-2])
match_avg_time = re.search(reg_avg_time, out)
avg_time = int(match_avg_time.group()[5:-2])
return [receive_count, min_time, max_time, avg_time]
else:
print(' Network is not accessible, the target server! ')
return [0, 9999, 9999, 9999]
if __name__ == '__main__':
ping_result = get_ping_result('114.80.83.69')
print(ping_result)
conclusion