我正在编写一个python程序,它可以ping设备并报告在线/离线状态和延迟。现在它工作正常,但只要有设备离线或没有响应输出挂起约5秒钟。
我的问题是我可以独立地ping所有内容而不是顺序地和/或我可以在子进程上设置某种时间过滤器,这样,如果在大约100-200ms之后没有更新,它会移动到下一个?
以下是我目前正在处理的代码的相关部分
for item in lines:
#remove whitespaces, etc from item.
hostname = item.rstrip()
#Run ping and return output to stdout.
#subprocess.Popen runs cmdline ping, pipes the output to stdout. .stdout.read() then reads that stream data and assigns it to the ping_response variable
ping_response = subprocess.Popen(["ping", hostname, "-n", '1'], stdout=subprocess.PIPE).stdout.read()
word = "Received = 1"
word2 = "Destination host unreachable."
#Regex for finding the time values and inputting them in to a list.
p = re.compile(ur'(?<=time[<=])\S+')
x = re.findall(p, ping_response)
if word2 in ping_response:
print "Destination Unreachable"
elif word in ping_response:
print "%s is online with latency of " % hostname +x[0]
else:
print "%s is offlineOffline" % hostname
答案 0 :(得分:2)
我的问题是我可以独立ping所有内容而不是顺序
不确定。该问题有多种解决方案,包括threading
和multiprocessing
模块。
和/或我可以在子流程上设置某种时间过滤器,这样,如果在大约100-200ms之后没有更新,那么它会移动到下一个过程吗?
您实际上可以使用ping
选项在-W
本身(至少是Linux版本)上设置超时:
-W timeout
Time to wait for a response, in seconds. The option affects only
timeout in absence of any responses, otherwise ping waits for
two RTTs.
答案 1 :(得分:2)
Ping
具有超时功能,可以帮助您提高脚本效率。
-W waittime
Time in milliseconds to wait for a reply for each packet sent. If a reply arrives later, the packet
is not printed as replied, but considered as replied when calculating statistics.
此外,here是其他一些有效ping的工具。