一种使用Windows下的python语言获取ping网络IP链接状态的方法
#!/usr/bin/python3#-*-coding:utf8-*-#!/usr/bin/pythonimportsubprocessimportredefLinkState(ip):returngetLinkState(ip)#获取链路状态defgetLinkState(ip):#运行ping程序p=subprocess.Popen(["ping.exe",ip],st...
#!/usr/bin/python3
# -*- coding:utf8 -*-
#!/usr/bin/python
import subprocess
import re
def LinkState(ip):
return getLinkState(ip)
# 获取链路状态
def getLinkState(ip):
#运行ping程序
p = subprocess.Popen(["ping.exe", ip],
stdin = subprocess.PIPE,
stdout = subprocess.PIPE,
stderr = subprocess.PIPE,
shell = True)
#得到ping的结果
out = p.stdout.read()
#找出丢包率,这里通过‘%’匹配
regex = re.compile(r'\w*%\w*')
packetLossRateList = regex.findall(str(out))
packetLossRate = packetLossRateList[0]
if packetLossRate == "0%":
print(packetLossRate)
return 1
else:
return 0
if __name__ == '__main__':
ip = '192.168.0.100' #要ping的主机
while True:
if LinkState(ip) == 1:
print("connected")
break
else:
print("not connected")
更多推荐
所有评论(0)