0
down vote
favorite
I have created a network scanner, that looks for a specific port on a range of IP's. I would like to thread the application but I am getting and error message

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

Now I understand why the error is there it is because the IP Address is not an INT. However, what I would prefer to do is split the subnet into equal parts and run X number of IP's on a per thread bases.

Example

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

Something along these lines. I"m not quite sure how to do this. I am posting the main function, the tcp ping and the threading function.

I suspect I need to get a list of IP's and then somehow tell the thread to execute on X number of IP's at a time but not really sure how to do that.

Thanks for the help in advance

# 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"

def tcp_port_ping(network):
    """

    :param network:
    :return:
    """

    tmp_iperf_list = []  # Temp iPerf List (Responders)
    total_ip_count = 0  # Total IP's in network
    active_ip_count = 0  # Total IP's Active, with port 2359 "OPEN"

    socket.setdefaulttimeout(MIN_SCAN_TIMEOUT)  # Setting Socket Time Out

    tcp_ping_start_time = datetime.now()  # Setting beginning time of scan

    # Scans for Active IP's with port 2359 Open
    for host in network.hosts():  # Determines Hosts for network

        total_ip_count += 1  # Total number of host counts

        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

    tcp_ping_end_time = datetime.now()

    tcp_ping_total_time = tcp_ping_end_time - tcp_ping_start_time

def main():
    """
    iPerf Accessory Discovery

    :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 the port scanner to run in threaded mode')

    try:
        args = parser.parse_args()
        if args.options:
            OPTION_FILE()

        if args.timeout:
            MIN_SCAN_TIMEOUT = args.timeout
            print(MIN_SCAN_TIMEOUT)

        if args.threading:
            threading()

        network = args.network  # Gets network from args parse mandatory argument

        # Calling Port Scanner
        network = (ipaddress.ip_network(network, strict=False))

        for x in range(30):
            t=threading.Thread(target=threader)
            t.daemon = True
            t.start()

        for worker in range(network.hosts):
            q.put(worker)

        q.join()

        tcp_port_ping(network)

    except KeyboardInterrupt as err_msg:
        logging.debug(err_msg)

    except OSError as err_msg:
        logging.debug(err_msg)

def threader():
    worker = q.get()
    tcp_port_ping(worker)
    q.task_done()

q = Queue

if __name__ == "__main__":
    main()

First off I let this question season since I'm not a python guru. But as I code in many languages the error looks to be that something expects an integer and that's it.

Read https://stackoverflow.com/questions/28036309/typeerror-list-object-cannot-be-interpreted-as-an-integer to see if this kicks the problem loose for you.

I can't tell which line is in error so I can't do much else but agree that the error message is telling us what is wrong.

What does worker in range(network.hosts) require? Some IP address? That may not be an integer but something like 10.0.0.2 or IP notation.

Here's an idea, you can ping by integer. Here's how. http://www.aboutmyip.com/AboutMyXApp/IP2Integer.jsp

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.