求解python2.7版本的一些问题,关于多线程活跃主机扫描的,代码跑起来就停止不了了,不知道为什么
#!/usr/bin/env python
#coding:utf-8
# Author: Zeroh
import os
import platform
import Queue
import threading
from IPy import IP
import pymysql
import time
printLock = threading.Semaphore(1) #lock Screen print
TimeOut = 5
def get_os():
'''
get os 类型
'''
os = platform.system()
if os == "Windows":
return "n"
else:
return "c"
class find_ip():
'''
给出当前的127.0.0 ,然后扫描整个段所有地址
'''
def __init__(self,cidr,threads_num):
self.threads_num = threads_num
self.cidr = IP(cidr)
#build ip queue
self.IPs = Queue.Queue()
for ip in self.cidr:
ip = str(ip)
self.IPs.put(ip)
def request(self):
with threading.Lock(): # 注意这里的改动
while self.IPs.qsize() > 0:
ip = self.IPs.get()
try:
cmd = ["ping", "-n" if get_os() == "n" else "-c", "1", ip] # 注意这里的改动
output = os.popen(" ".join(cmd)).readlines()
flag = False
for line in output:
if line.upper().find("TTL") >= 0:
flag = True
break
if flag:
print("ip: %s is ok ***" % ip) # 注意这里的改动
except Exception as e: # 注意这里的改动
printLock.acquire()
print("Exception occurred: %s" % e) # 打印异常信息
printLock.release()
def run(self):
for i in range(self.threads_num):
t = threading.Thread(target=self.request)
t.start()
def main(cidr):
# print cidr
print "start time %s" % time.ctime()
options={'threads_num': 200}
s = find_ip(cidr,threads_num=options['threads_num'])
s.run()
print "end time %s" % time.ctime()
return
# main('127.0.0.1')
main('192.168.242.0/24')