Windows command prompt in Python

Question:

I have the following code which captures traffic packets, write them into a traffic.pcap file, then convert the pcap to text file using the tshark. If I enter the full path and name of the files in the last line, the code works perfectly, however it is always overwriting the files, so I added the lines to add time to each file so I can save all, the sniff and write commands work as expected, they create a new name each time I run it and save the file with the new name, however, when the code reaches the last line, it does not recognize the name of the file (source and destination) to read and convert, any help would be appreciated.

from scapy.all import *
import time
import os
# Create a new unique name
if os.path.exists('D:/folder/traffic.pcap'):
    file_name = ('D:/folder/traffic_{}.pcap'.format(int(time.time())))
# Create a destination file
txt_file = file_name + '.txt'
# Sniff traffic and write to a file *.pcap
x = sniff(count=10)
wrpcap(file_name,x)
# Convert pcap file to txt file usign tshark command
#os.system('cmd /c "tshark -i - < "D:/folder/traffic.pcap" > "D:/folder/traffic.txt""')# working line
os.system('cmd /c "tshark -i - < %file_name% > %txt_file%"')#not working line

The output is generated by the last line is The system cannot find the file specified.

Asked By: Ali

||

Answers:

%file_name% is a cmd variable.
You need to use the python variable.

You can access the python variable via
f'cmd /c "tshark -i - < {file_name} > {txt_file}"'
(An f string f"string", works like .format.)

The system call does not run in python. It forks (well creates) a new process. After creation, the processes do not communicate. Not even pipes. You can use the process module to create processes with some interprocess communication, however they won’t have access to each other’s variables.

The replacement line is: os.system(f'cmd /c "tshark -i - < {file_name} > {txt_file}"')

You may also wish to consider bash as your shell.

Answered By: ctrl-alt-delor
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.