My environment is Python + Linux
I've a program which can be run from command line . After running when user press ctrl+c it saves some data in a output file(In my case the program is tcpdump and it stores sniffed packet in pcap file after user press ctrl+c).Without Ctrl+C the program doesn't exit / stop.
I've to run this program tcpdump via a thread and after some operation I have to stop the thread and collect the pcap file.
My Code:
class MyClass(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
self.process = None
self.stdout = None
self.stderr = None
def run(self):
print '[+] Starting Sniffer at : ',Interface
cmd = 'tcpdump -i lo tcp port 8080 -w hello.pcap'
p = subprocess.Popen(cmd.split(),shell=False,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
self.stdout, self.stderr = p.communicate()
def stop(self):
print "[+] Trying to stop the sniffer thread.."
if self.process is not None:
self.process.terminate()
self.process = None
print '[+] Thread stopped'
s = MyClass()
s.start()
#some operation
s.stop()
# some opes
The the problem I'm facing I get empty pcap file. I thought may be because one of the following problems, its happening
Maybe because without ctrl+C it doesn't save the output to pcap file. Is there any solution / hack for this, to forcefully save this ?
I think, the thread is not stopping even after execution of s.stop(). I've confirmed this using s.is_alive(). I'm getting True before and after s.start() and s.stop()
Thanks,