我想为机器人框架创建两个关键字来捕获网络流量。 开始抓包 停止抓包
这是networkcapturelibrary.py的内容
import pyshark, threading
class NetworkCaptureLibrary:
def __init__(self):
self.capture = None
self.stop_execution = False
def _start_package_capture_in_background(self, interface, file_name):
self.capture = pyshark.LiveCapture(interface=interface, output_file=file_name)
self.capture.sniff()
for _ in self.capture:
if self.stop_execution:
break
def start_package_capture(self, interface, file_name):
self.capture = pyshark.LiveCapture(interface=interface, output_file=file_name)
self.background_thread = threading.Thread(target=self._start_package_capture_in_background, args=(interface, file_name))
self.background_thread.start()
def stop_package_capture(self):
if self.capture:
self.stop_execution = True
self.background_thread.join()
这是test.robot的内容
*** Settings ***
Library NetworkCaptureLibrary.py
*** Test Cases ***
Capture Traffic Test
Start Package Capture Ethernet captured_traffic.pcap
Sleep 10s # Capture traffic for 10 seconds (optional)
Stop Package Capture
我使用 self.stop_execution 来标记何时完成后台进程。
脚本在执行时失败并出现以下错误:File "C:\Python311\Lib hreading.py", line 1038, in _bootstrap_inner
你能建议一下,可能是什么问题吗?
我通过直接在线程中启动嗅探来简化启动和停止捕获的过程。您不需要额外的功能来启动嗅探
class NetworkCaptureLibrary:
def __init__(self):
self.thread = None
def start_package_capture(self, interface, file_name):
capture = pyshark.LiveCapture(interface=interface, output_file=file_name)
self.thread = threading.Thread(target=capture.sniff)
self.thread.start()
def stop_package_capture(self):
self.thread.join(timeout=0)