Inserting a nested bash command in Python

I have the following bash command in which I take tcpdump and then save the file using the date command. I want to embed this command directly into my Python script instead of having to call the bash script separately.

#!/bin/bash
timeout 2 tcpdump -i eth1 -s 96 -w /usr/src/pcapFiles/dump$(date +%y%m%d-%H%M%S).pcap

      

I get the following types of filenames when I run the above script that I want (i.e. the date and time are shown in the name):

dump131104-191834.pcap

However, I am having difficulty reproducing the above command from Python. I got this far from implementing a command in Python. I'm not sure how to split the date command so that it can display the filename the same way it did to me. Below is my Python command:

tcpd = subprocess.Popen(["timeout", "2", "tcpdump", "-i", "eth1", "-s", "96", "-w", "/usr/src/pcapFiles/dump$(date +%y%m%d-%H%M%S).pcap"], stdout=subprocess.PIPE)
output, err = tcpd.communicate()

      

With this command I am getting the following output filenames from tcpdump

dump$(date +%y%m%d-%H%M%S).pcap

0


source to share


1 answer


$(..)

since command expansion is done by the shell. Since you're using Python instead of a shell, you don't get this feature for free.

A simple fix is ​​to invoke the shell and give it the command:

tcpd = subprocess.Popen(["bash", "-c", "timeout 2 tcpdump -i eth1 -s 96 -w /usr/src/pcapFiles/dump$(date +%y%m%d-%H%M%S).pcap"], stdout=subprocess.PIPE)
output, err = tcpd.communicate()

      



Perhaps a more correct fix is ​​to get the current date in Python:

import datetime
filename=datetime.datetime.now().strftime("/usr/src/pcapFiles/dump%y%m%d-%H%M%S.pcap")
tcpd = subprocess.Popen(["timeout", "2", "tcpdump", "-i", "eth1", "-s", "96", "-w", filename, stdout=subprocess.PIPE)
output, err = tcpd.communicate()

      

+4


source







All Articles