使用socket模块,多线程扫描指定ip的端口开放情况

使用socket模块,多线程扫描指定ip的端口开放情况

#!/usr/bin/env python
# -*- coding: utf-8 -*-


import sys
import socket
import optparse
import threading
import queue


# 端口扫描类,继承threading.Thread
class PortScaner(threading.Thread):
    # 需要传入 端口队列 目标IP 探测超时时间
    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
            # 从端口队列中取出端口,超时时间为1s
            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))
                # sys.stdout.write("[%d]Scan\n" % port)
                # 若端口开放则会返回0
                if result_code == 0:
                    sys.stdout.write("[%d] OPEN\n" % port)

            except Exception as e:
                print(e)

            finally:
                s.close()


# 启动扫描方法
def StartScan(targetip, port, threadNum):
    # 端口列表
    portList = []

    portNumb = 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地址
    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()

#219.150.184.218 104.21.27.222

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')
    # 目标IP参数-i
    parser.add_option('-i', '--ip', dest='targetIP', default='127.0.0.1', type='string', help='target IP')
    # 添加端口参数-p
    parser.add_option('-p', '--port', dest='port', default='80', type='string', help='scann port')
    # 线程数量参数-t
    parser.add_option('-t', '--thread', dest='threadNum', default=100, type='int', help='scann thread number')

    (options, args) = parser.parse_args()

    StartScan(options.targetIP, options.port, options.threadNum)

执行结果:

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值