!/usr/bin/python
-- coding: utf-8 --
"""
@version: ??
@author: Guanjie Zhou
@license: Apache Licence
@file: dis_port_threading.py
@time: 17-5-27 上午8:21
"""
import socket
import time
import threading
socket.setdefaulttimeout(1)
建立存放开放端口的列表
open_port = []
锁
lock = threading._allocate_lock()
线程列表
threads = []
计数器
openNum = 0
端口扫描函数
def socket_port(ip, port):
global openNum
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 返回连接结果,成功的话返回为0,失败返回errno的值
# 这里要注意的是下边的函数里边的为(ip, port)一个整体
result = s.connect_ex((ip, port))
if result == 0:
lock.acquire()
print '[+] %d open' % port
open_port.append(port)
openNum += 1
lock.release()
except:
print u"端口扫描异常"
def ip_scan(ip, port_range=65535):
# 输入ip地址后,扫描在范围内的端口占用情况
try:
start_time = time.time()
for port in range(0, port_range):
t = threading.Thread(target=socket_port, args=(ip, int(port)))
# 将线程加入线程列表
threads.append(t)
t.start()
# 线程加join
for t in threads:
t.join()
end_time = time.time()
print u'[] %s扫描完成,总共用时: %.2f' % (ip, (end_time - start_time))
print u'[] 一共开放%d端口,具体如下: ' % (openNum)
print open_port
except:
print u"端口扫描出错"
if name == 'main':
# 输入要扫描的端口号
url = raw_input('Input the ip whitch you want to scan: ')
# 输入要扫描的范围
port_range = raw_input(u"输入要扫描的最大端口: ")
# 判断为空的时候,设置一个默认值
if not port_range:
port_range = 65535
ip_scan(url, int(port_range))