假设我们要检查本地网络中哪些IP地址是可达的哪些是不可达的,我们可以用循环来实现,也可以用线程来实现。
不用线程的实现方式:
#!/usr/bin/python
import os, re, threading, commands, time
status = ["no respones","alive, but 50% package loss","alive","shouldn't occur"]
received_packages = re.compile(r"(\d) received")
for suffix in range(20,29):
ip = "10.170.9."+str(suffix)
ping_out = os.popen("ping -c 2 " + ip ,"r")
while True:
line = ping_out.read()
if not line:
break
n_received = re.findall(received_packages, line)
if n_received:
print "Status from ", ip, " is ", status[int( n_received[0])],time.ctime(time.time())
执行结果:
Status from 10.170.9.20 is alive Fri Apr 17 13:57:03 2015