指定端口号,多线程扫描局域网内IP地址

小白第一次发博客,请各路大神不要喷,有错的地方还请不吝啬指教,谢谢。。。。。。。

因为注释基本上已经说清楚啦,在这里就不多说什么啦,知识不够怕误人子弟

# -*- coding:utf-8 -*-
import socket
import time
import threading

def Scan(IpAddr,port,thread_num,i):

number = 254 / thread_num #f每个线程将要处理的IP数
# 通过变量i来判断线程处理的哪个IP段,然后循环处理
for p in range(number * (i + 1),number * i,-1):
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM) # 通过 IPV4协议 数据流 形式创建socket对象
addr = IpAddr + '.' + str(p) # IP地址
try:
s.connect((addr,int(port))) # 通过对端口进行连接来判断的开关
s.close()
print(addr) # 输出开该端口的IP地址
except socket.error:
pass
#如果该端口没有打开,是会抛出[10061] Connection refused等异常

def main(IpAddr,port,thread_num):
threads = [] # 线程列表
number = 254 / thread_num # 每个线程的处理的IP数
number_end = 254 % thread_num # 剩下的IP地址
num = range(thread_num)

# 将创建的所有线程加入线程列表中
for i in num:
t = threading.Thread(target=Scan,args=(IpAddr,port,thread_num,i))
threads.append(t)

# 启动所有线程
for i in num:
threads[i].start()

# 挂起程序,等待所有线程结束
for i in num:
threads[i].join()

# 这里是为了当在函数Scan传入的thread_num线程数不能整除254时,
# 会导致后面的IP地址漏扫描
if number_end > 0:
for i in range(255,number * thread_num):
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
addr_e = IpAddr + '.' + str(i)
try:
s.connect((addr_e,int(port)))
s.close()
print(addr_e)
except socket.error:
pass

测试代码:
if __name__=='__main__':

IpAddr = raw_input('please input the IP segement:')
port = raw_input('please input the port:')
threadNum = raw_input('please input the number of threads:')
start_time = time.time()
main(IpAddr,port,int(threadNum))
end_time = time.time()
print('total time is : %s' %(end_time-start_time))

效果:

please input the IP segement:172.16.135
please input the port:3389
please input the number of threads:20
172.16.135.12
172.16.135.11
172.16.135.48
172.16.135.60

   ....

http://www.cnblogs.com/GHost-Ma/
原文地址:https://www.cnblogs.com/GHost-Ma/p/5284747.html