2014-04-27 31 views
0

Sory爲我的英語不好。也許問題已經解決,但不幸的是我還沒有找到解決我的問題。一般來說,任務存在問題。有人能幫我嗎? 使用scapy和netinfo,我需要創建功能,它向系統中的默認網絡接口(類似於'ethX',其中X是數字)發送「8.8.8.8」主機的ping請求,並驗證請求已被 通過捕獲傳出數據包發送。如何使用scapy和netinfo創建腳本來捕獲數據包?

這一步,我部分的理解:

#!/usr/bin/python 

import sys 
from scapy.all import * 
import netinfo 
class test: 
    host = "8.8.8.8" 

    def pingh(self): 
     self.host 
     pkt = Ether()/IP(dst=self.host,ttl=(1,3))/ICMP() 
     ans,unans = srp(pkt,iface="eth0",timeout=2) 
     ans.summary(lambda (s,r): r.sprintf("%Ether.src% %IP.src%")) 

r = test() 
print "request from ping " 
r.pingh() 

,但在下一步我被卡住了:

同時執行相同的「LO」和「的ethX」接口(使用標準的「穿透'模塊)。 捕獲的結果應該收集到具有以下結構的字典中: {'iface1':list_of_captured_pa​​ckets,'iface2':list_of_captured_pa​​ckets,...}。修改此字典應該是線程安全的。通過添加一個測試來修改測試類,該測試檢查結果字典是否包含'lo'和'ethX'接口作爲關鍵字。 P. S. 不要讓我死個傻子:)

回答

0

下使用threading模塊做兩個平行ping測試,一個在每兩個接口。對於未來的工作,使用multiprocessing模塊與Pool()imap_unordered() - 這是一個更容易。

# INSTALL: 
# sudo apt-get install python-scapy 
# RUN: 
# sudo /usr/bin/python ./pping.py 

import sys, Queue, threading 
from scapy import all as S 

IFACE_LIST = 'wlan0','lo' 


# pylint:disable=E1101 
def run_ping(iface, out_q): 
    host = '8.8.8.8' 
    pkt = S.Ether()/S.IP(dst=host, ttl=(1,3))/S.ICMP() 
    ans,_unans = S.srp(pkt, iface=iface, timeout=2) 
    out_q.put((iface,ans)) 


result_q = Queue.Queue() 
for iface in IFACE_LIST: 
    threading.Thread(
     target=run_ping, args=(iface, result_q) 
    ).start() 

for t in threading.enumerate(): 
    if t != threading.current_thread(): 
     t.join() 

print 'result:', dict([ 
    result_q.get() 
    for _ in range(result_q.qsize()) 
    ]) 

輸出:

Begin emission: 
Begin emission: 
..Finished to send 3 packets. 
*Finished to send 3 packets. 
...** 
Received 5 packets, got 3 answers, remaining 0 packets 
.................... 
Received 23 packets, got 0 answers, remaining 3 packets 
result: {'lo': <Results: TCP:0 UDP:0 ICMP:0 Other:0>, 'wlan0': <Results: TCP:0 UDP:0 ICMP:3 Other:0>}