Making a Fast Port Scanner

前端 未结 9 723
眼角桃花
眼角桃花 2021-02-03 12:48

So I\'m making a port scanner in python...

import socket
ip = \"External IP\"
s = socket.socket(2, 1) #socket.AF_INET, socket.SOCK_STREAM

def porttry(ip, port):         


        
相关标签:
9条回答
  • 2021-02-03 13:24

    here is a quick and simple port scanner, it scans 100000 ports in 180 sec:

    import threading
    import socket
    
    target = 'pythonprogramming.net'
    #ip = socket.gethostbyname(target)
    
    def portscan(port):
    
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.settimeout(0.5)# 
    
        try:
            con = s.connect((target,port))
    
            print('Port :',port,"is open.")
    
            con.close()
        except: 
            pass
    r = 1 
    for x in range(1,100): 
    
        t = threading.Thread(target=portscan,kwargs={'port':r}) 
    
        r += 1     
        t.start() 
    
    0 讨论(0)
  • 2021-02-03 13:31

    I think that this one snippet could help you : http://www.coderholic.com/python-port-scanner/

    0 讨论(0)
  • 2021-02-03 13:35

    In addition to setting socket timeout, you can also apply multi-threading technique to turbo boost the process. It will be, at best, N times faster when you have N ports to scan.

    # This script runs on Python 3
    import socket, threading
    
    
    def TCP_connect(ip, port_number, delay, output):
        TCPsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        TCPsock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        TCPsock.settimeout(delay)
        try:
            TCPsock.connect((ip, port_number))
            output[port_number] = 'Listening'
        except:
            output[port_number] = ''
    
    
    
    def scan_ports(host_ip, delay):
    
        threads = []        # To run TCP_connect concurrently
        output = {}         # For printing purposes
    
        # Spawning threads to scan ports
        for i in range(10000):
            t = threading.Thread(target=TCP_connect, args=(host_ip, i, delay, output))
            threads.append(t)
    
        # Starting threads
        for i in range(10000):
            threads[i].start()
    
        # Locking the main thread until all threads complete
        for i in range(10000):
            threads[i].join()
    
        # Printing listening ports from small to large
        for i in range(10000):
            if output[i] == 'Listening':
                print(str(i) + ': ' + output[i])
    
    
    
    def main():
        host_ip = input("Enter host IP: ")
        delay = int(input("How many seconds the socket is going to wait until timeout: "))   
        scan_ports(host_ip, delay)
    
    if __name__ == "__main__":
        main()
    
    0 讨论(0)
  • 2021-02-03 13:35

    The following port scanner has a few constants defined at the top that you can modify as needed:

    • PURPOSE -- help message for the command line
    • PORTS -- range of ports you would like scanned
    • POOL_SIZE -- number of processes to scan with
    • TIMEOUT -- how long to wait for server connection

    Feel free to adapt this according to your requirements. Maybe add some command line arguments?

    #! /usr/bin/env python3
    import argparse
    import collections
    import itertools
    import multiprocessing
    import operator
    import socket
    
    PURPOSE = 'Scan for open ports on a computer.'
    PORTS = range(1 << 16)
    POOL_SIZE = 1 << 8
    TIMEOUT = 0.01
    
    
    def main():
        """Get computer to scan, connect with process pool, and show open ports."""
        parser = argparse.ArgumentParser(description=PURPOSE)
        parser.add_argument('host', type=str, help='computer you want to scan')
        host = parser.parse_args().host
        with multiprocessing.Pool(POOL_SIZE, socket.setdefaulttimeout, [TIMEOUT]) \
                as pool:
            results = pool.imap_unordered(test, ((host, port) for port in PORTS))
            servers = filter(operator.itemgetter(0), results)
            numbers = map(operator.itemgetter(1), servers)
            ordered = sorted(numbers)
        print(f'Ports open on {host}:', *format_ports(ordered), sep='\n    ')
    
    
    field_names = 'family', 'socket_type', 'protocol', 'canon_name', 'address'
    AddressInfo = collections.namedtuple('AddressInfo', field_names)
    del field_names
    
    
    def test(address):
        """Try connecting to the server and return whether or not it succeeded."""
        host, port = address
        for info in itertools.starmap(AddressInfo, socket.getaddrinfo(host, port)):
            try:
                probe = socket.socket(info.family, info.socket_type, info.protocol)
            except OSError:
                pass
            else:
                try:
                    probe.connect(info.address)
                except OSError:
                    pass
                else:
                    probe.shutdown(socket.SHUT_RDWR)
                    return True, port
                finally:
                    probe.close()
        return False, port
    
    
    def format_ports(ports):
        """Convert port numbers into strings and show all associated services."""
        if ports:
            for port in ports:
                try:
                    service = socket.getservbyport(port)
                except OSError:
                    service = '?'
                yield f'{port:<5} = {service}'
        else:
            yield 'None'
    
    
    if __name__ == '__main__':
        main()
    
    0 讨论(0)
  • 2021-02-03 13:36

    Consider setting a timeout instead of a for loop by using socket.setdefaulttimeout(timeout).

    0 讨论(0)
  • 2021-02-03 13:44

    socket.setdefaulttimeout(0.5) This will make the program faster!

    0 讨论(0)
提交回复
热议问题