Making a Fast Port Scanner

前端 未结 9 726
眼角桃花
眼角桃花 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:47

    socket.setdefualttimeout (time)

    is used to keep trying to connect with port for perticular time...when you send request and there is timeout set for 2 seconds so it will try to connect with port for 2 seconds....if there will be no response from that port in 2 seconds....it will be count as a dead port

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

    One can use threading.Thread and threading.Condition to synchronize port check and spawning new threads.

    Script example usage:

    python port_scan.py google.com 70 90
    Checking 70 - 80
    Checking 80 - 84
    Checking 84 - 90
    Found active port 80
    Checking 90 - 91
    Checking 91 - 94
    All threads started ...
    

    port_scan.py:

    # import pdb
    import socket, threading
    from traceback import print_exc
    
    
    class AllThreadsStarted(Exception): pass
    
    
    class IPv4PortScanner(object):
        def __init__(self, domain, timeout=2.0, port_range=(1024, 65535), threadcount=10):
            self.domain               = domain
            self.timeout              = timeout
            self.port_range           = port_range
            self.threadcount          = threadcount
            self._lock                = threading.Lock()
            self._condition           = threading.Condition(self._lock)
            self._ports_active        = []
            self._ports_being_checked = []
    
            self._next_port = self.port_range[0]
    
        def check_port_(self, port):
            "If connects then port is active"
            sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
            sock.settimeout(self.timeout)
            try:
                sock.connect((self.domain, port))
                with self._lock:
                    self._ports_active.append(port)
                print ("Found active port {}".format(port))
                sock.close()
            except socket.timeout, ex:
                return
            except:
                print_exc()
                # pdb.set_trace()
    
        def check_port(self, port):
            "updates self._ports_being_checked list on exit of this method"
            try:
                self.check_port_(port)
            finally:
                self._condition.acquire()
                self._ports_being_checked.remove(port)
                self._condition.notifyAll()
                self._condition.release()
    
        def start_another_thread(self):
            if self._next_port > self.port_range[1]:
                raise AllThreadsStarted()
            port             = self._next_port
            self._next_port += 1
            t = threading.Thread(target=self.check_port, args=(port,))
            # update books
            with self._lock:
                self._ports_being_checked.append(port)
            t.start()
    
        def run(self):
            try:
                while True:
                    self._condition.acquire()
                    while len(self._ports_being_checked) >= self.threadcount:
                        # we wait for some threads to complete the task
                        self._condition.wait()
                    slots_available = self.threadcount - len(self._ports_being_checked)
                    self._condition.release()
                    print ("Checking {} - {}".format(self._next_port, self._next_port+slots_available))
                    for i in xrange(slots_available):
                        self.start_another_thread()
            except AllThreadsStarted, ex:
                print ("All threads started ...")
            except:
                print_exc()
    
    
    if __name__ == "__main__":
        import sys
        domain  = sys.argv[1]
        port_s  = int(sys.argv[2])
        port_e  = int(sys.argv[3])
        scanner = IPv4PortScanner(domain=domain, port_range=(port_s, port_e))
        scanner.run()
    
    0 讨论(0)
  • 2021-02-03 13:49

    This should be a bit faster.

    #-*-coding:utf8;-*-
    #qpy:3
    #qpy:console
    
    import socket
    import os
    
    # This is used to set a default timeout on socket
    # objects.
    DEFAULT_TIMEOUT = 0.5
    
    # This is used for checking if a call to socket.connect_ex
    # was successful.
    SUCCESS = 0
    
    def check_port(*host_port, timeout=DEFAULT_TIMEOUT):
        ''' Try to connect to a specified host on a specified port.
        If the connection takes longer then the TIMEOUT we set we assume
        the host is down. If the connection is a success we can safely assume
        the host is up and listing on port x. If the connection fails for any
        other reason we assume the host is down and the port is closed.'''
    
        # Create and configure the socket.
        sock = socket.socket()
        sock.settimeout(timeout)
    
        # the SO_REUSEADDR flag tells the kernel to reuse a local 
        # socket in TIME_WAIT state, without waiting for its natural
        # timeout to expire.
        sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    
        # Like connect(address), but return an error indicator instead
        # of raising an exception for errors returned by the C-level connect() 
        # call (other problems, such as “host not found,” can still raise exceptions). 
        # The error indicator is 0 if the operation succeeded, otherwise the value of 
        # the errnovariable. This is useful to support, for example, asynchronous connects.
        connected = sock.connect_ex(host_port) is SUCCESS
    
        # Mark the socket closed. 
        # The underlying system resource (e.g. a file descriptor)
        # is also closed when all file objects from makefile() are closed.
        # Once that happens, all future operations on the socket object will fail. 
        # The remote end will receive no more data (after queued data is flushed).
        sock.close()
    
        # return True if port is open or False if port is closed.
        return connected
    
    
    con = check_port('www.google.com', 83)
    print(con)
    
    0 讨论(0)
提交回复
热议问题