我正在写一个脚本,如果我的网络掉了或者我的服务器掉了,它会提醒我。代码如下:
import subprocess
import time
iplist=["127.0.0.1","8.8.8.8"]
#iplist=["127.0.0.1","8.8.8.8", "983.42.23.342"]
def Pingisdown(ip, p):
timeouts = time.time()
p.wait()
while p.poll():
timeout = time.time()
print(ip)
print(timeout - timeouts)
#length
if p.poll() == 0:
break
print("YAYYY")
for ip in iplist:
p = subprocess.Popen('ping '+ip,stdout=subprocess.PIPE)
p.wait()
if p.poll():
Pingisdown(ip, p)
else:
print (ip+" is up")问题是,当我启用我的网络,一旦它备份,它仍然被算作离线。如果离线,则p.poll返回1;如果im正确,则返回0。在while循环中的任何一种情况下,只要我重新打开它,它就会一直记录为1。
编辑:
我已经使用所提供的代码的很好的一部分对其进行了修改。它没有使用while,而是使用if条件,这是因为ping all ready重复。这现在起作用了。
import subprocess
import time
iplist=["127.0.0.1","8.8.8.8"]
#iplist=["127.0.0.1","8.8.8.8", "983.42.23.342"]
def Pingisdown2(ip, p, timeouts):
p = subprocess.Popen('ping '+ip,stdout=subprocess.PIPE)
p.wait()
if p.poll():
Pingisdown(ip, p, timeouts)
else:
print (ip+" is up")
timeout = time.time()
print(timeout - timeouts)
def Pingisdown(ip, p, timeouts):
print(ip)
Pingisdown2(ip, p, timeouts)
for ip in iplist:
p = subprocess.Popen('ping '+ip,stdout=subprocess.PIPE)
p.wait()
if p.poll():
timeouts = time.time()
Pingisdown(ip, p, timeouts)
timeout = time.time()
else:
print (ip+" is up")发布于 2018-06-25 19:33:30
您不会在每次调用wait()或poll()时都再次运行ping -您只是从第一次运行中获得结果。因此,如果它失败了,那么每次调用poll()时,结果仍然是失败的。
发布于 2018-06-25 19:39:05
因为您对ping命令调用的状态码感兴趣,所以使用subprocess.check_call会更合适。另外,将args作为列表传递,而不是字符串,这是从python调用bash命令的首选方式,请参见下面的while循环的主体:
try:
# I've added -i and -c flags for fast ping command. Run `man ping` in terminal for flags description.
subprocess.check_call(['ping', '-c', '5', '-i', ' 0.2', ip])
except subprocess.CalledProcessError:
Pingisdown(ip) # NOTE: Update to process only ip.
else:
print (ip+ " is up")请让我知道,如果错误不会消失后,应用建议的处理。
https://stackoverflow.com/questions/51022298
复制相似问题