Scapy 变量嗅探器

Scapy variable sniff stop

我发现了一个类似的问题: (), 但仍然不知道我的任务的解决方案。

任务是在测试脚本完成后停止 scapy 嗅探功能。 运行 单个测试脚本的持续时间可以有很大差异(从几秒到几小时)。我的嗅探功能在单独的威胁中运行。测试脚本在开始时调用一个 init Funktion,它从另一个模块调用 sniff 函数。

@classmethod
    def SaveFullTrafficPcap(self, TestCase, Termination):
        try:
            Full_Traffic = []
            PktList = []
            FullPcapName = Settings['GeneralSettings']['ResultsPath']+TestCase.TestCaseName +"Full_Traffic_PCAP.pcap"
            #while Term.Termination < 1:             
            Full_Traffic = sniff(lfilter=None, iface=str(Settings['GeneralSettings']['EthInterface']), store=True, prn = lambda x: Full_Traffic.append(x), count=0, timeout=Term.Termination)
            print(Full_Traffic)   
            wrpcap(FullPcapName, Full_Traffic)
        except(Exception):
            SYS.ABS_print("No full traffic PCAP file wirtten!\n")

在测试脚本的末尾调用退出函数。在退出函数中,我将 Term.Termination 参数设置为 1 并等待 5 秒,但它不起作用。嗅探功能被系统停止,我没有得到文件"FullPCAPName" 如果计数或超时得到一个值,代码可以正常工作,我得到我的 FullPCAPName 文件,他在我的界面上完成了流量。

有没有人告诉我如何在完成测试脚本后定期停止嗅探功能?

现在我解决了全局变量的问题。不是很好,但效果很好。

尽管如此,我对变量嗅探停止的更好解决方案很感兴趣。

使用 stop_filter 命令作为指定 here worked for me. I've duplicated HenningCash's 为方便起见,下面的代码:

import time, threading
from scapy.all import sniff
e = threading.Event()
def _sniff(e):
    a = sniff(filter="tcp port 80", stop_filter=lambda p: e.is_set())
    print("Stopped after %i packets" % len(a))

print("Start capturing thread")
t = threading.Thread(target=_sniff, args=(e,))
t.start()

time.sleep(3)
print("Try to shutdown capturing...")
e.set()

# This will run until you send a HTTP request somewhere
# There is no way to exit clean if no package is received
while True:
    t.join(2)
    if t.is_alive():
        print("Thread is still running...")
    else:
        break

print("Shutdown complete!")

但是,您仍然需要等待嗅探最后一个数据包,这在您的场景中可能并不理想。

stop_var = ""
def stop():
    global stop_var
    stop_var.stop()



def start():
    """
    your code
    """
    global stop_var
    stop_var = AsyncSniffer(**arg)
    stop_var=start()