Python3 scapy區域網自動多執行緒arp掃描實現
阿新 • • 發佈:2021-02-04
一、所需Python庫
from scapy.all import *
import threading
二、實現ip掃描
1.獲取c段ip地址
在ARP()裡面有ip地址,我們可以從裡面提取出前3段出來
ARP().show()
然後通過從後查詢最後一個.得到最後一段位數,然後總長度-最後一段長度就能取出前3段
tip=ARP().psrc
print(tip[:(len(tip)-tip[::-1].find('.'))])
2.arp掃描函式實現
然後就是建立函式實現掃描了,構造arp包->傳送包->判斷是否響應->輸出資訊
def ScanIp(ip):
pkt=Ether(dst="ff:ff:ff:ff:ff:ff")/ARP(pdst=ip)
res=srp1(pkt,timeout=10,verbose=0)
if res:
print(res.psrc)
print(res.hwsrc)
然後來在加個判斷返回的ip跟我們要掃描的ip是否一致,然後加上異常處理
def ScanIp(ip): pkt=Ether(dst="ff:ff:ff:ff:ff:ff")/ARP(pdst=ip) try: res=srp1(pkt,timeout=10,verbose=0) if res.psrc==ip: print(res.psrc) print(res.hwsrc) except: pass
現在把輸出結果美化一下,不然直接print很難看
def ScanIp(ip):
pkt=Ether(dst="ff:ff:ff:ff:ff:ff")/ARP(pdst=ip)
try:
res=srp1(pkt,timeout=10,verbose=0)
if res.psrc==ip:
print('IP MAC')
print('[+]'+res.psrc+' '+res.hwsrc)
except:
pass
嘗試呼叫一下
ScanIp('192.168.123.1')
現在看起來就很舒服
3.多執行緒
現在我們只需要迴圈一下c段ip然後用多執行緒跑起來就行了
for i in range(1,256):
ip=tip+str(i)
Go=threading.Thread(target=ScanIp,args=(ip,))
Go.start()
然後看一下效果好像不是我們想要的因為IP MAC輸出了很多次看起來很難受
然後這裡把輸出移動到函式外的for迴圈上方,然後判斷一下__name__,這樣就完成了所有的功能了
from scapy.all import *
import threading
tip=ARP().psrc
tip=tip[:(len(tip)-tip[::-1].find('.'))]
def ScanIp(ip):
pkt=Ether(dst="ff:ff:ff:ff:ff:ff")/ARP(pdst=ip)
try:
res=srp1(pkt,timeout=10,verbose=0)
if res.psrc==ip:
print('[+]'+res.psrc+' '+res.hwsrc)
except:
pass
if __name__=='__main__':
print('IP MAC')
for i in range(1,256):
ip=tip+str(i)
Go=threading.Thread(target=ScanIp,args=(ip,))
Go.start()
執行效果