小言_互联网的博客

Python 实现端口扫描

265人阅读  评论(0)

突然发现用python随意得写写代码也还是不错的:不考虑代码的严谨性; 不考虑面向对象的事情,突然又找到了当初学习C语言时的感觉

import os
import sys
import time
import socket
from multiprocessing import Queue
import thread as _thread
star_time = time.time()
host = socket.gethostname()
port = 9999
print( host )
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
s.bind( (host,port) )
addr, m_port = s.getsockname()

print( addr )
'''
print( type(addr), type(m_port) )
'''
def _port_scan(ip, port, timeout):
	try:
		s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
		s.settimeout(timeout)
		result_code = s.connect_ex((ip, port))
		if result_code == 0:
			sys.stdout.write("% 6d [OPEN]\n"%port)
			return port
		else:
			return
	except Exception as e:
		print(e)
	finally:
		s.close()
		
def port_scan(ip, port_list, timeout):
	result_list = list()
	for port in port_list:
		ret_port = _port_scan(ip, port, timeout)
		if ret_port != None:
			result_list.append(ret_port)
	return result_list

thread_num = 400	
port_list = range(1, 65536)
#result_list = port_scan(addr, port_list, 3)
port_queue = Queue()
for port in port_list:
	port_queue.put(port)

def PortScan(ip, port_queue, timeout=3):
	while port_queue.empty() == False:
		port = port_queue.get()
		_port_scan(ip, port, timeout)
''' Threads '''	
for t in range(thread_num):
	try:
		#print(t)
		_thread.start_new_thread( PortScan, (addr,port_queue) )
	except:
	   print ("Error: unable to start thread")



while 1:
	pass
	if port_queue.empty():
		s.close()
		end_time = time.time()
		print "[End time] %3ss"%(end_time-star_time)
		exit()

 


转载:https://blog.csdn.net/cpq37/article/details/101215843
查看评论
* 以上用户言论只代表其个人观点,不代表本网站的观点或立场