小白第一次發博客,請各路大神不要噴,有錯的地方還請不吝啬指教,謝謝。。。。。。。
因為注釋基本上已經說清楚啦,在這裡就不多說什麼啦,知識不夠怕誤人子弟
# -*- 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
....