如何使用scapy和netinfo创建捕获数据包的脚本?

0 投票
1 回答
1761 浏览
提问于 2025-04-18 04:30

抱歉我的英语不好。也许这个问题已经解决了,但不幸的是我还没有找到我问题的答案。总的来说,我在任务上遇到了问题。有人能帮我吗?

我在使用scapy和netinfo时,需要创建一个功能,能够向“8.8.8.8”这个主机发送ping请求,并且要通过系统中的默认网络接口(类似于'ethX',其中X是数字)来发送这些请求,同时捕获到发送出去的数据包,以验证请求是否已经发送。

在这个步骤中,我部分理解了:

#!/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'接口做同样的操作(使用标准的'threading'模块)。捕获到的结果应该收集到一个字典中,这个字典的结构应该是这样的:{'iface1': 捕获的数据包列表, 'iface2': 捕获的数据包列表, ...}。这个字典的修改应该是线程安全的。修改测试类,添加一个测试,检查结果字典中是否同时包含'lo'和'ethX'接口作为键。

附注:别让我死得太傻 :)

1 个回答

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>}

撰写回答