python 多线程 实现端口扫描

# -*- coding: utf-8 -*-
#!/usr/bin/python2
from socket import *
import threading
 
lock = threading.Lock()
openNum = 0
 
def portScanner(host,port):
  global openNum
  try:
    s = socket(AF_INET,SOCK_STREAM)
    s.connect((host,port))
    lock.acquire()
    openNum+=1
    print('[+] %d open' % port)
    lock.release()
    s.close()
  except:
    pass
 
def main():
  setdefaulttimeout(1)
  for n in range(1,76):
    threads = []
    #print (n-1)*880,n*880
    for p in range((n-1)*880,n*880):
      t = threading.Thread(target=portScanner,args=('127.0.0.1',p))
      threads.append(t)
      t.start()
 
    for t in threads:
      pass
    t.join()#在子线程完成运行之前,这个子线程的父线程将一直被阻塞。
 
  print('[*] The scan is complete!')
  print('[*] A total of %d open port ' % (openNum))
 
if __name__ == '__main__':
  main()

执行结果:

[+] 135 open
[+] 443 open
[+] 903 open
[+] 913 open
[+] 1536 open
[+] 1537 open
[+] 1538 open
[+] 1542 open
[+] 1548 open
[+] 1556 open
[+] 2869 open
[+] 4000 open
[+] 4300 open
[+] 4301 open
[+] 5939 open
[+] 7680 open
[+] 8307 open
[+] 8363 open
[+] 8382 open
[+] 8911 open
[+] 8912 open
[+] 12037 open
[+] 12056 open
[+] 13790 open
[+] 14979 open
[+] 23405 open
[+] 28317 open
[+] 29917 open
[+] 49152 open
[+] 61078 open
[*] The scan is complete!
[*] A total of 30 open port 


for p in range(1,1024):
      t = threading.Thread(target=portScanner,args=('127.0.0.1',p))
      threads.append(t)
      t.start()

出错:thread.error: can't start new thread

本人计算机的最大并发线程是866,这里有1024,超过最大线程数导致出错

TCP/IP协议中的端口,端口号的范围从0到65535,扫描65535个端口的状况.

for n in range(1,76):
    threads = []
    #print (n-1)*880,n*880
    for p in range((n-1)*880,n*880):
      t = threading.Thread(target=portScanner,args=('127.0.0.1',p))
      threads.append(t)
      t.start()
 
    for t in threads:
      pass
    t.join()#在子线程完成运行之前,这个子线程的父线程将一直被阻塞。


你可能感兴趣的:(python,多线程,多进程)