python使用socket实现多线程端口扫描

版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/comprel/article/details/72825562

使用socket主要是判断是否端口能否联通
socket<<详情参考>>

1.socket.connect() 检测端口,若端口不能联通,则会抛出异常,若无异常,则端口存活,使用try-except异常捕获处理,进而进行端口扫描

这里将使用100个线程,每个端口连接都要检查是否超过65535

#coding=utf8
import socket
import threading


def scan(host,cport):
    for x in range(660):
       p=x+660*cport
       try:
         if p < 65535:
             s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
             s.connect((host, p))
             s.settimeout(0.1)
             print "local open port : %d"%p
             s.close()
         else :
             break
       except Exception:
           pass

list = []
for i in range(100):
        t = threading.Thread(target=scan,args=('localhost',i,))
        list.append(t)
        t.start()

for threadinglist in list:
        threadinglist.join()

输出:

local open port : 22
local open port : 111
local open port : 34172
local open port : 49716
local open port : 51078

2.socket.connect_ex() 若联通则返回为0,否则返回为非0
依据connect_ex返回值判断端口是否存活

import socket 
import threading 
from Queue import Queue 

def scan(port): 
  s = socket.socket() 
  s.settimeout(1) 
  if s.connect_ex(('localhost', port)) == 0: 
     print "local open port : %d"%port
  s.close() 

def worker(): 
  while not q.empty(): 
    port = q.get() 
    try: 
      scan(port) 
    finally: 
      q.task_done() 

if __name__ == '__main__': 
  q = Queue() 
  map(q.put,xrange(1,65535)) 
  threads = [threading.Thread(target=worker) for i in xrange(100)] 
  map(lambda x:x.start(),threads) 
  q.join() 

输出:

local open port : 22
local open port : 25
local open port : 111
local open port : 631
local open port : 35156
local open port : 38929
local open port : 51078
展开阅读全文

没有更多推荐了,返回首页