1, Python single threaded scan port, code as follows:
code is as follows |
copy code |
#!/usr/bin/env python #coding: UTF8 Import socket IP = ' Www.111cn.net for port in range (1,1024,1): sk = Socket.socket (socket.af_inet, socket. SOCK_STREAM) sk.settimeout (2) print "Scanning port:%d"% port & nbsp Try: sk.connect ((ip,port)) print ' Server%s port%d OK '% (ip,port) except Exception: ; print ' Server%s port%d is not connected! '% (ip,port) Sk.close () |
/tbody>
2, Python multi-process scan port, the code is as follows:
The code is as follows |
Copy Code |
#!/usr/bin/env python #coding: UTF8 Import socket Import Sys Import multiprocessing Import time
def test (Port): ip = ' www.chlinux.net ' Port = Int (port) Print Port SK = Socket.socket (socket.af_inet, socket. SOCK_STREAM) Sk.settimeout (0.5) Print "Scanning ports:%d"% port Try Sk.connect ((Ip,port)) Print "Server%s port%d OK"% (ip,port) Except Exception: Print "Server%s port%d is not connected!"% (Ip,port) Sk.close ()
if __name__ = = ' __main__ ': Pool = multiprocessing. Pool (PROCESSES=20) For port in Xrange (1,65535): Port = Int (port) Pool.apply_async (test, Port,) Pool.close () Pool.join () Print "sub-process (es) done." |