tools--port scan

程序代碼如下:

# -*- coding: utf-8 -*-
# 多線程端口掃描主程序
# Author:Bing
# Contact:amazing_bing@outlook.com
# Date:2016.11.14

import threading, socket, sys, os, Queue

class ScannerThread(threading.Thread):
    def __init__(self, inq, outq):
        threading.Thread.__init__(self)
        # queues for (host, port)
        self.setDaemon(True)        #主程序等待任務隊列
        self.inq = inq              #掃描隊列
        self.outq = outq            #結果隊列
        self.killed = False
        self.timeout = 0.5

    def run(self):
        while not self.killed:
            host, port = self.inq.get()
            sd = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            sd.settimeout(self.timeout)
            try:
                # connect to the given host:port
                sd.connect((host, port))
                self.outq.put((host, port, 'OPENED'))
            except socket.error:
                # set the CLOSED flag
                self.outq.put((host, port, 'CLOSED'))             
            sd.close()

        
class Scanner:
    def __init__(self, from_port, to_port, host='localhost'):
        self.from_port = from_port
        self.to_port = to_port
        self.host = host
        self.scanners = []

    def scan(self, search_for='opened',first_match=False, nthreads=1,send_fn=None, exclude=[]):
        """
        @param search_for(string): Search for 'opened', 'closed' or 'all' ports
        @param first_match(bool): If True returns only first scan result and stoping scanning
        @param nthreads(int): Number of threads
        @param send_fn(function): Callback to send results data
        @param exclude(list(int)): Ports not to be to scanned
        @return(list): list of tuples(host, port, status)
        """
        self.resp = []
        if self.from_port>self.to_port:
            print ("'from port' must be smaller than 'to port'")
            return
        #生成任務隊列
        toscan = Queue.Queue()
        scanned = Queue.Queue()
        #生成掃描線程
        self.scanners = [ScannerThread(toscan, scanned) for i in range(nthreads)]
        #print self.scanners
        #線程準備開始
        for scanner in self.scanners:
            scanner.start()
        #把端口和主機壓入隊列,exclude黑名單
        hostports = [(self.host, port) for port in xrange(self.from_port, self.to_port+1) if port not in exclude]
        #print hostports
        for hostport in hostports:
            toscan.put(hostport)

        results = {}
        for host, port in hostports:
            while (host, port) not in results:
                nhost, nport, nstatus = scanned.get()       #獲取結果隊列的值
                results[(nhost, nport)] = nstatus
            status = results[(host, port)]
            value = (host, port, status)
            print value
            if status == 'OPENED' and search_for.lower() == 'opened':
                if send_fn:
                    send_fn(value)
                if first_match:
                    return self._finish_scan()
            elif status == 'CLOSED' and search_for.lower() == 'closed':
                if send_fn:
                    send_fn(value)
                if first_match:
                    return self._finish_scan()
            elif search_for.lower() == 'all':
                if send_fn:
                    send_fn(value)
                if first_match:
                    return self._finish_scan()
        return self._finish_scan()

    #殺死線程
    def _finish_scan(self):
        for scanner in self.scanners:
            scanner.join(0.001)
            scanner.killed = True
        return self.resp

result = []
callback = lambda x: result.append(x)
scanner = Scanner(1, 200, "127.0.0.1")
scanner.scan(search_for='opened', first_match=False, nthreads=100, send_fn=callback)
print result








'''
def baidu(a,b):
    print str(a)+str(b)

acy = []

def service():
    count = 0 
    pool = Pool(100)
    simple = GetQueue(txt)
    while not simple.empty():
        p = simple.get()
        count = count+1
        print gevent.getcurrent(),count
        acy.append(gevent.spawn(scan_app_service,p[0],p[1]))
        #g = gevent.spawn(scan_app_service,p[0],p[1])
        #g.join()
        #pool.add(gevent.spawn(scan_app_service,p[0],p[1]))
    #pool.join()
    gevent.joinall(acy)
#service()

#print gevent.getcurrent()
#print scan_app_service(p[0],p[1])

'''
最后編輯于
?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容