用来学习Threading、Queue的组合使用,实现多线程编程。
实现功能
利用 ping 来检测主机是否存活。
代码如下:
# _*_coding:utf-8_*_
from IPy import IP
from subprocess import Popen, PIPE
from Queue import Queue
import threading,sys
class ping_check(threading.Thread):
def __init__(self,queue):
threading.Thread.__init__(self)
self._queue = queue
def run(self):
while not self._queue.empty():
ip = self._queue.get_nowait()
try:
check = Popen(['ping', ip], stdin=PIPE, stdout=PIPE)
data = check.stdout.read()
if 'TTL' in data:
sys.stdout.write('%s is live!' % ip + '\n')
else:
pass
except Exception,e:
pass
#将C段IP地址:127.0.0.1/24 转换为单个IP
def ip_create(ips):
queue = Queue()
ip = IP(ips, make_net=True)
for i in ip:
i = str(i)
queue.put(i)
return queue
def main(ips):
queue = ip_create(ips)
threads = []
thread_count = 20
for i in range(thread_count):
threads.append(ping_check(queue))
for t in threads:
t.start()
for t in threads:
t.join()
if __name__ == '__main__':
if len(sys.argv) == 2:
main(sys.argv[1])
else:
print "use:%s 127.0.0.1/24"%sys.argv[0]