1

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

  1. 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 ?

  2. 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,

Dev.K.
  • 2,428
  • 5
  • 35
  • 49
  • You must demonize your script in normal way. Try like this: http://stackoverflow.com/questions/1603109/how-to-make-a-python-script-run-like-a-service-or-daemon-in-linux – pulina Jul 06 '15 at 12:44
  • The "empty" file is probably because of buffering. Call `flush()` on the file object, or `close()` it. – cdarke Jul 06 '15 at 13:12
  • I think Ctrl+C will just terminate the program, are you catching it in your application and stopping appropriately? Also, are you running the script as root? – nick_v1 Jul 06 '15 at 13:52

0 Answers0