python-端口探测

python-端口探测

背景:

有些时候,在工作过程中,遇到服务器数量非常多。应用模块部署在不同服务器上。有时维护人员做了模块迁移,而未及时同步至手册中。查找比较困难。于是,产生Python根据应用端口进行探测,获取模块部署。查看服务器开放的服务端口,更好的利用。

代码:

import sys
import socket
import optparse
import threading
import queue


class PortScaner(threading.Thread):
    def __init__(self, portqueue, ip, timeout=3):
        threading.Thread.__init__(self)
        self._portqueue = portqueue
        self._ip = ip
        self._timeout = timeout

    def run(self):
        while True:
            if self._portqueue.empty():
                break
            port = self._portqueue.get(timeout=0.5)
            try:
                s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                s.settimeout(self._timeout)
                result_code = s.connect_ex((self._ip, port))
                if result_code == 0:
                    sys.stdout.write("[%d]Scan\n" % port)
            except Exception as e:
                print(e)
            finally:
                s.close()


def StertScan(targetip, port, threadNum):
    portList = []
    portNumber = port
    if '-' in port:
        for i in range(int(port.split('-')[0]), int(port.split('-')[1]) + 1):
            portList.append(i)
        else:
            portList.append(int(port))
        ip = targetip
        threads = []
        threadNumber = threadNum
        portQueue = queue.Queue()
        for port in portList:
            portQueue.put(port)
        for t in range(threadNumber):
            threads.append(PortScaner(portQueue, ip, timeout=3))
        for thread in threads:
            thread.start()
        for thread in threads:
            thread.join()


if __name__ == "__main__":
    parser = optparse.OptionParser(
        'Example: python %prog -i 127.0.0.1 -p 80 \n      python %prog -i 127.0.0.1 -p 1-100\n')
    parser.add_option('-i', '--ip', dest='targetIP', default='127.0.0.1', type='string', help='target IP')
    parser.add_option('-p', '--port', dest='port', default='80', type='string', help='scann port')
    parser.add_option('-t', '--thread', dest='threadNum', default=100, type='int', help='scann thread number')
    options, args = parser.parse_args()
    StertScan(options.targetIP, options.port, options.threadNum)

猜你喜欢

转载自blog.csdn.net/qq_48985780/article/details/121640466