栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

python-端口探测

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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]Scann" % 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-100n')
    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)

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/619012.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号