Import Socketimport threading# Create receive route list routers = []# Create Mutex lock = Threading. Lock () # Sets the list of port numbers that need to be scanned port_list = [' 3389 ', ' 2425 ', ' 139 ']# definition query route function def search_routers (): # Get a list of local IP addresses local_ips = socket.get HOSTBYNAME_EX (Socket.gethostname ()) [2] # print (local_ips) # Store thread list Pool all_threads = [] # loop local NIC IP list for IP in local_ips:for I in range (1, 255): # Put the NIC IP "." partition, generate a list of each available address array = Ip.split ('. ') # gets the fourth digit after the split, generating all available IP addresses for that segment array[3] = str (i) # put a list of each available address after the split, with "." Connect to generate a new IP new_ip = '. '. Join (Array) # print (NEW_IP) # traverse the list of port numbers that need to be scanned for port in port_list:dst_port = Int (port) # Loop creates a thread to link that address T = Threading. Thread (TARGET=CHECK_IP, args= (NEW_IP, Dst_port)) T.start () # Put the new thread into the thread pool All_threads.append (t) # Loop blocks the main thread, waiting for each sub-thread to finish executing, The program then exits for T in All_threads:t.join () # Create Access IP list Method def check_ip (NEW_IP, Port): # Create a TCP socket, link a new IP list scan_link = Socket.socket ( Socket.af_inet, Socket. SOCK_STREAM) # Set link timeout time scan_link.settimeout (2) # link address (by specifying the host address we constructed, and scanning the specified port) result = SCAN_LINK.CONNECT_EX (NEW_IP, Port) # Scan_link.closE () # print (Result) # determine the link result if result = = 0: # plus lock Lock.acquire () print (NEW_IP, ' \t\t port number%s open '% port) routers.append ((new_i P, Port) # release Lock Lock.release () # print (routers) print ("Scanning ..., please wait ...") # Launcher Entry if __name__ = = ' __main__ ': # Start scanner Search_ Routers ()
Python specifies port scan for LAN