python2.7版本写了一个活跃主机扫描的代码,用的多线程,现在想将扫描的结果存活主机IP保存至MySQL数据库,但多线程不是很明白,应该怎么修改代码
# !/usr/bin/env python
# coding:utf-8
# Author: Zeroh
import os
import platform
import multiprocessing
from IPy import IP
import pymysql
from socket import setdefaulttimeout
import time
printLock = multiprocessing.Lock() # lock Screen print
TimeOut = 5
def get_os():
'''
get os 类型
'''
os = platform.system()
if os == "Windows":
return "n"
else:
return "c"
class find_ip():
def __init__(self, cidr, threads_num):
self.threads_num = threads_num
self.cidr = IP(cidr)
self.IPs = multiprocessing.Queue()
for ip in self.cidr:
self.IPs.put(str(ip))
def request(self):
while not self.IPs.empty():
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:
with printLock: # 使用多进程锁
print("ip: %s is ok ***" % ip)
try:
sqlAdd='insert into activeipscan(IP)VALUES ("%s;")'%ip
cursor.execute(sqlAdd)
db.commit()
except Exception,e:
print'2',e
except Exception as e:
with printLock: # 使用多进程锁
print("Exception occurred: %s" % e)
def run(self):
for i in range(self.threads_num):
multiprocessing.Process(target=self.request).start()
def main(cidr):
global db,cursor
try:
db=pymysql.connect('localhost','root','root','test')
cursor=db.cursor()
sqlDelete='delete from activeipscan'
cursor.execute(sqlDelete)
db.commit()
except Exception,e:
print '1',e
setdefaulttimeout(1)
# 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())
if __name__ == "__main__":
main('192.168.242.0/24')