0

The below command is running one time and saves abc.pcap to directory. I want the below command to run continous and make pcaps of five second but file names should be different, it continously make 5 sec pcaps untill I stop it.

from subprocess import run
       
command = 'tcpdump -i eno1 -w abc.pcap'
output = run(command, capture_output=True, shell=True, timeout=5).stdout.decode()
print(" capture packet for 5 seconds")
Traceback (most recent call last):
  File "one.py", line 17, in <module>
    output = run(command.format(str(file_counter)), capture_output=True, shell=True,timeout=5).stdout.decode()
  File "/usr/lib/python3.8/subprocess.py", line 491, in run
    stdout, stderr = process.communicate(input, timeout=timeout)
  File "/usr/lib/python3.8/subprocess.py", line 1024, in communicate
    stdout, stderr = self._communicate(input, endtime, timeout)
  File "/usr/lib/python3.8/subprocess.py", line 1867, in _communicate
    self._check_timeout(endtime, orig_timeout, stdout, stderr)
  File "/usr/lib/python3.8/subprocess.py", line 1068, in _check_timeout
    raise TimeoutExpired(
subprocess.TimeoutExpired: Command 'tcpdump -i eno1 -w abc_0.pcap' timed out after 5 seconds

1 Answers1

1

A simple while loop should do the job

from subprocess import Popen,PIPE
import time
    
command = 'tcpdump -i wlp2s0 -w capture_{}.pcap'

file_counter = 0 
while True:
    proc = Popen(command.format(str(file_counter)),shell=True)
    time.sleep(5)
    proc.terminate()
    print("Capture ",file_counter)
    
    
    file_counter += 1

print("Captured packet for 5 seconds")

I used Popen instead of run and switched the dump interface to wlp2s0 because that way I could test it, but your interface should be work too with this code. Btw, you have to execute this program with sudo so that tcpdump has the permissions to access the interface.
Instead of having a counter you should probably have the time as/in the filename.

lightstack
  • 321
  • 2
  • 8