Search code examples
pythontcpdump

saving tcpdump as variable


I am trying to read the data from a tcpdump but I am not getting the correct output

import socket
import colorama
import time
import os
import csv
from datetime import datetime

colorama.init()
BLUE = colorama.Fore.BLUE
GRAY = colorama.Fore.LIGHTBLACK_EX
RED = colorama.Fore.RED
GREEN = colorama.Fore.GREEN
YELLOW = colorama.Fore.YELLOW
RESET = colorama.Fore.RESET

def preservation():
    def data():
        data = os.system('tcpdump -i en0 -z 192.168.0.1 -c 10')
        return data
    signal = str(data())
    print(f'{RED}{signal}{RESET}')
    while True:
        if 'seavers-mbp' in signal:
            now = datetime.now()
            print(f'{RED}***PACKET FOUND***{RESET}')
            print("now =", now)
            dt_string = now.strftime("%d/%m/%Y %H:%M:%S")
            caught = [(dt_string), (signal)]
            with open('watchdog.csv' 'a') as file:
                file_writer = csv.writer(file)
                file_writer.writerow(caught)
        print(f'{BLUE}cycle complete{RESET}')
        time.sleep(.5)
        signal = str(data())


preservation()

signal comes back as 0 instead of the actual tcpdump do I have to save it to a pcap file and read that file or is it possible to save the output as a variable

(btw I am running this script as superuser)


Solution

  • os.system(command) does return the exit code of the command and not the output.

    The documentation states (https://docs.python.org/3/library/os.html#os.system):

    Execute the command (a string) in a subshell. This is implemented by calling the Standard C function system(), and has the same limitations. Changes to sys.stdin, etc. are not reflected in the environment of the executed command. If command generates any output, it will be sent to the interpreter standard output stream.

    So you will need to redirect the output to a file or use the subprocess module to get the calls stdout