Python 实现端口扫描

突然发现用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()

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值