队列+多线程扫描内网80,8080存活主机脚本

#!-*- coding:utf-8 -*-
import sys,requests,re,os
import threading,Queue
"""
#单线程运行
ip = "10.1.5.0"
count = 5
file_object = open('host.txt', 'w')

ip2 = int(ip.split('.')[-2])
ip1 = int(ip.split('.')[-1])
ip_before = '%s.%s' % (ip.split('.')[0], ip.split('.')[1])
for i in xrange(0,count,1):
    new_ip1 = ip1 + i
    if  11 <= new_ip1 <= 254:
        print '%s.%s.%s' % (ip_before, str(ip2), str(new_ip1))
    else:
        new_ip2 = ip2 + int(new_ip1/254)
        new_ip1 = new_ip1%254 + 10
        host = '%s.%s.%s' % (ip_before, str(new_ip2), str(new_ip1))
        try:
            print host,
            url1="http://"+host
            url2="http://"+host+":8080"
            if requests.get(url=url1,timeout=5).status_code == 200 :
                file_object.write(url1+"\n")
                print url1,u"success"
            elif requests.get(url=url2,timeout=5).status_code == 200 :
                file_object.write(url2+"\n")
                print url2,u"success"
        except:
            print host,u"error"
else:
    file_object.close()
    print u"end!!!"
"""

#转换 ip函数
def ip2num(ip):
    ip=[int(x) for x in ip.split('.')]
    return ip[0] <<24 | ip[1]<<16 | ip[2]<<8 |ip[3]
def num2ip(num):
    return '%s.%s.%s.%s' %( (num & 0xff000000) >>24,
                            (num & 0x00ff0000) >>16,
                            (num & 0x0000ff00) >>8,
                            num & 0x000000ff )
def get_ip(ip):
    start,end = [ip2num(x) for x in ip.split('-') ]
    return [ num2ip(num) for num in xrange(start,end+1) if num & 0xff ]

#线程类
class myThread (threading.Thread):
    def __init__(self, threadID, name, q):
        threading.Thread.__init__(self)
        self.threadID = threadID #线程id,每次增加1
        self.name = name #线程名从1到NUM
        self.q = q #队列标识
    def run(self):
        process_data(self.name, self.q)

# 调用线程 执行
def process_data(threadName, q):
    #循环条件:exitFlag=0
    while not exitFlag:
        #线程加锁
        queueLock.acquire()
        #如果队列不为空
        if not workQueue.empty():
            #不为空则获取队列
            ip = q.get()
            queueLock.release()
            #线程解锁
            print  u"\n\n[loading: %s/%s ]" % (zongshu - workQueue.qsize(), zongshu)
            #自定义需要验证/实现的方法
            _verify(ip)
        else:
            #线程解锁
            queueLock.release()

def _verify(host):
    #实现可以打开的话,则保存到文件中
    with open('host.txt', 'a') as file_object:
        try:
            #print host,
            url1="http://"+host
            url2="http://"+host+":8080"
            response1=requests.get(url=url1,timeout=5)
            response2=requests.get(url=url2,timeout=5)

            if response1.status_code == 200 :
                title = re.findall(r'<title>(.*?)</title>', response1.content)[0]
                file_object.write(url1+','+title+"\n")
                print url1,title,u"success"
            if response2.status_code == 200 :
                title = re.findall(r'<title>(.*?)</title>', response2.content)[0]
                file_object.write(url2+','+title+"\n")
                print url2,title,u"success"
        except:
            print host,u"error"
        #file_object.close()


if __name__ == '__main__':
    # 线程退出标志
    exitFlag = 0
    #默认线程数量
    NUM = 100
    #线程锁
    queueLock = threading.Lock()
    #消息队列
    workQueue = Queue.Queue()
    #线程列表
    threads = []
    #队列线程id
    threadID = 1

    #创建线程组(一个列表)
    for tName in xrange(1,NUM):
        #调用线程类
        thread = myThread(threadID, tName, workQueue)
        #线程开始
        thread.start()
        #添加到线程列表
        threads.append(thread)
        #线程id自增
        threadID += 1        

    #获取ip列表
    #iplist=get_ip('10.132.0.0-10.132.255.255')
    iplist=get_ip('10.1.0.0-10.1.255.255')

    #获取ip列表总数
    zongshu=len(iplist)

    #加锁
    queueLock.acquire()
    #遍历ip列表
    for host in iplist:
        #添加到队列
        workQueue.put(host)
    #解锁
    queueLock.release()

    #等待队列清空
    while not workQueue.empty():
        pass
   
    # 通知线程退出
    exitFlag = 1

    # 等待所有线程完成`
    for t in threads:
        #线程阻塞
        t.join()

    print u"-- END  ---"

发表评论

电子邮件地址不会被公开。 必填项已用*标注

This site uses Akismet to reduce spam. Learn how your comment data is processed.