将 tcpdump 保存为变量

saving tcpdump as variable

我正在尝试从 tcpdump 读取数据,但没有得到正确的输出

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()

信号返回为 0 而不是实际的 tcpdump 我必须将它保存到 pcap 文件并读取该文件还是可以将输出保存为变量

(顺便说一句,我是 运行 这个脚本的超级用户)

os.system(command) return 命令的退出代码而不是输出。

文档指出 (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.

因此您需要将输出重定向到文件或使用 subprocess 模块来获取调用 stdout