主要利用threading结合queue的特性构建多线程框架,重写threading的run发发,利用socket模块验证端口是否开启
import threading
import queue
import sys, os
from socket import *
import time
class portscan(threading.Thread):
def __init__(self, q):
threading.Thread.__init__(self)
self.__queue = q
def run(self):
while not self.__queue.empty():
port = self.__queue.get()
self.brute(port)
def brute(self, port):
host='192.168.78.180'
s=socket(AF_INET,SOCK_STREAM)
s.settimeout(5)
# sys.stdout.write("---------------当前进程名称:%s,正在扫描端口:%s-----------------\n" %(self.name,port))
try:
s.connect((host, port))
sys.stdout.write("[*]Port:%d open \n" % (port))
sys.stdout.flush()
with open(r'openport.txt','a+') as f:
f.write("[*]Port:%d open \n" % (port))
s.close()
except:
s.close()
if port>=65536:
stop_time = time.time()
print("[*]cost time %s" % (stop_time - start_time))
os._exit(0)
def main():
global start_time
start_time=time.time()
threads = []
thread_num = 1000
q = queue.Queue()
for i in range(1,65537):
q.put(int(i))
for t in range(thread_num):
t = portscan(q)
threads.append(t)
for i in threads:
i.start()
for i in threads:
i.join()
if __name__ == "__main__":
main()
查看目标机器开放端口:
扫描结果:
[*]Port:21 open
[*]Port:22 open
[*]Port:23 open
[*]Port:111 open
[*]Port:2049 open
[*]Port:3306 open
[*]Port:5900 open
[*]Port:6379 open
[*]Port:8080 open
[*]Port:8081 open
[*]Port:8989 open
[*]Port:9000 open
[*]Port:9200 open
[*]Port:11211 open
[*]Port:22222 open
[*]Port:35954 open
[*]Port:38667 open
[*]Port:39725 open
[*]Port:41920 open
[*]Port:43971 open
1000个线程耗时65秒多扫完65535个端口