Run pyshark in background

Viewed 468

I'd like to run pyshark in the background so while its running I'll still be able to perform some web actions and capture them. One mandatory condition is that I must be able to parse using tshark because I have some proprietary Wireshark dissectors.

Basically what I need to do is this:

  1. Start network capture
  2. Perform some web actions
  3. Stop capture (or wait for a stop condition)
  4. Iterate over capture object and check each packet's properties

I can't use capture.sniff() as-is because it's working in blocking mode, and can't use capture.sniff_continuously() because it's a generator.

Problem: I tried calling sniff() from a thread, then wait for it to end with join(). But when I reach the iterator, tshark.exe relaunch and overwrites the capture file:

print('Background sniffing:')
capture = pyshark.LiveCapture(interface='Ethernet', bpf_filter='host 10.20.30.40', output_file='bg_capture.pcapng')
t = threading.Thread(target=capture.sniff, kwargs={'timeout': 30, 'packet_count': 5000}, daemon=True)
t.start()
print('Do some stuff web action here...')
t.join()
print('Done sniffing')
for p in capture: # At this point, tshark re-launch itself
    print(f'Packet number {p.number}')
0 Answers
Related