Howto:线程将子网拆分为子列表,并为每个列表生成一个线程

时间:2017-06-13 15:45:56

标签: python linux multithreading python-3.x python-multithreading

我创建了一个网络扫描程序,用于查找一系列IP上的特定端口。我想线程化应用程序,但我得到了错误消息

ERROR:
for worker in range(network.hosts):
TypeError: 'method' object cannot be interpreted as an integer

现在我理解为什么会出现错误,因为IP地址不是INT。但是,我更愿意做的是将子网分成相等的部分,并在每个线程基础上运行X个IP。

实施例

Thread 1 192.168.1 - 30
Thread 2 192.168.31 - 60
Thread 3 192.168.61 - 90
Thread 4 192.168.91 - 120
Thread 5 192.168.121 - 150
Thread 6 192.168.151 - 180
Thread 7 192.168.181 - 210
Thread 8 192.168.211 - 240
Thread 9 192.168.241 - 254

这些方面的东西。我不太清楚如何做到这一点。我发布了主要功能,tcp ping  和线程功能。

我怀疑我需要获取一个IP列表,然后以某种方式告诉线程一次执行X个IP,但不确定如何做到这一点。

感谢您的帮助

好像你不能在名单上开始工作?这是我目前关于错误消息的地方。其他线程似乎有相同的错误消息。这是jsut输出的最后一行。

Exception in thread Thread-27:
Traceback (most recent call last):
  File "/usr/local/Cellar/python3/3.6.1/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 916, in _bootstrap_inner
    self.run()
  File "/usr/local/Cellar/python3/3.6.1/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 864, in run
    self._target(*self._args, **self._kwargs)
TypeError: threader() argument after * must be an iterable, not type



  File "pyportscanner", line 366, in 
    main()
  File "pyportscanner", line 154, in main
    for worker in range(iperf[0:]):
TypeError: 'list' object cannot be interpreted as an integer

代码:

 # Library Imports
from datetime import datetime
from queue import Queue
import threading
import argparse
import logging
import os
import socket
import ipaddress


# Defines Global Variables
BUFFER = 4096  # 4k The size of the TCP Buffer
MESSAGE = 'TA:getattrlong'.encode('utf-8')
TCP_PORT = 2359  # Sets Port to 2359 (iPerf Remote)
MIN_SCAN_TIMEOUT = .010  # Sets Min socket timeout to 10ms 'milliseconds'
MAX_SCAN_TIMEOUT = .160  # Sets Max socket timeout to 100ms 'milliseconds'
IPERF_QUERY_TIMEOUT = 5  # Sets socket timeout to 5s 'seconds'

# File I/O Vars
LOG_FILE = 'iperfdiscovery.log'  # Testing log, revert to above on actual AirCheck G2
IPERF_ACCESSORY_FILE = 'iperfaccessory'  # iPerf Accessory output file
OPTION_FILE = '/mnt/mmc3/iperfaccessory.conf'  # iPerf Accessory option file "Allows increasing timeout"

THREADS = 50


def main():
    """
    iPerf Accessory Discovery Utility for AirCheck G2 V2.0

    :return:
    """
    # Logging (File Location, Log level, date, message)
    logging.basicConfig(filename=LOG_FILE, filemode='w', level=logging.DEBUG, format='%(asctime)s %(message)s')

    # Removes iPerf Accessory File if its exists File Output Logs errors
    # NOTE: File cannot be found is normal in the log expected behavior
    try:
        os.remove(IPERF_ACCESSORY_FILE)
    except OSError as err_msg:
        logging.debug('DEBUG: OS Error %s', err_msg)
        pass

    # Arg Parser
    parser = argparse.ArgumentParser()
    parser.add_argument('network', help='The IP/Network you wish to scan', type=str)
    parser.add_argument('-t', '--timeout', nargs='?', const=1, type=float, help='Optional socket timeout')
    parser.add_argument('-v', '--version', action='version', version='%(prog)s 1.9')
    parser.add_argument('-o', '--options', action='store_true',
                        help='Uses the advanced configuration options if present')
    parser.add_argument('-th', '--threading', action='store_true',
                        help="Enables multiple threads")

    try:
        args = parser.parse_args()
        network = args.network  # Gets network from args parse mandatory argument
        network = (ipaddress.ip_network(network, strict=False))

        if args.options:
            OPTION_FILE()

        if args.timeout:
            MIN_SCAN_TIMEOUT = args.timeout
            print(MIN_SCAN_TIMEOUT)
        if args.threading:
            q = Queue
            iperf = []
            subnet = []

            for host in network.hosts():  # List of IP's in subnet
                subnet.append(str(host))

            for i in range(0, len(subnet), THREADS):
                iperf.append(subnet[i: i + THREADS])

            for x in range(THREADS):
                t = threading.Thread(target=threader, args=q)
                t.daemon = True
                t.start()

            for worker in range(iperf[0:]):
                q.put(worker)

            q.join()

        else:
            tcp_port_ping(network)

    except KeyboardInterrupt as err_msg:
        logging.debug(err_msg)

    except OSError as err_msg:
        logging.debug(err_msg)


def threader(q):
    while True:
        worker = q.get()
        t_tcp_port_ping(worker)
        q.task_done()


def t_tcp_port_ping():

    active_ip_count = 0
    tmp_iperf_list = []

    try:
        with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as tcp_sock:
            result = tcp_sock.connect_ex((str(host), TCP_PORT))  # Check if IP is Valid and Port is Open
            if result == 0:
                active_ip_count += 1  # Increment valid IP counter
                tmp_iperf_list.append(host)  # Appends iPerf attributes to iPerf Remote list
                logging.debug("DEBUG: IP(s) to be scanned %s", host)  # Debug IP Address of remote(s)

    except OSError as err_msg:
        logging.debug('Socket Error %s', err_msg)
        print(err_msg)
        pass

    print(tmp_iperf_list)

0 个答案:

没有答案