def win_ping_avg_time(ip_address):
p = subprocess.Popen(["ping", ip_address], stdin=subprocess.PIPE, stdout=subprocess.PIPE,
stderr=subprocess.PIPE, shell=True)
out = p.stdout.read().decode('gbk')
# 依次将其中的值取出来
reg_receive = '已接收 = \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: # 接受到的反馈大于0,表示网络通
reg_avg_time = '平均 = \d+ms'
match_avg_time = re.search(reg_avg_time, out)
avg_time = int(match_avg_time.group()[5:-2])
# print(f'"ping_时间":{start_time} "ping_平均响应时间":{avg_time}')
return str(avg_time)
# write_file(str(start_time) + "," + str(avg_time) + "\n", self.csv_file)
else:
return str(-1)
def linux_ping_avg_time(ip_address):
ping_out = subprocess.getoutput("ping -c 4 -w 60 %s" % ip_address)
#-c 4 几次 -w 60间隔多少s
if '/avg' in ping_out:
avg_time = ping_out.split('/')[-3]
return avg_time
else:
# 如果到间隔时间ping不通,则返回-1
return str(-1)
做兼容
def can_ping(ip_address):
try:
if platform.system().lower() == 'windows':
win_ping_avg_time(ip_address)
else:
linux_ping_avg_time(ip_address)
return True
except Exception as e:
return False