1. 程式人生 > >python 多執行緒 實現埠掃描

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()#在子執行緒完成執行之前,這個子執行緒的父執行緒將一直被阻塞。