Tshark 未通过 subprocess.Popen 执行

Tshark not executing through subprocess.Popen

我正在尝试在 python 中执行 tshark,如下所示:

class ARPSniffer:
    def testTshark(self, iface):
        print("Testing if tshark works. Using {}".format(iface))

        cmd = "tshark -i " + iface
        args = shlex.split(cmd)
        tshark = subprocess.Popen(args, stdout=PIPE)
        for line in io.TextIOWrapper(tshark.stdout, encoding="utf-8"):
            print(line)

    def run(self, iface):
        try:
            t = Thread(target=self.testTshark, args=(iface, ))
            t.daemon = True
            t.start()
            t.join
        except KeyboardInterrupt:
            print("\nExiting ARP monitor...")
            sys.exit(0)

if __name__ == '__main__':
    iface = 'wlan1'
    arps = ARPSniffer()
    arps.run(iface)

它打印 "Testing if tshark works. Using wlan1" 但 tshark 没有启动。我用top查了一下,没有任何进程运行。我究竟做错了什么?我 运行 它使用 sudo。

谢谢大家。

正如@Rawing 在评论中指出的那样,t.join 上有一个拼写错误。 如果你想立即看到输出数据包,你还应该使用 tshark 的 -l 选项。否则 tshark 会缓冲它们。

import subprocess
from threading import Thread
import shlex
import sys
import io

class ARPSniffer:
    def testTshark(self, iface):
        print("Testing if tshark works. Using {}".format(iface))

        cmd = "tshark -l -i " + iface
        args = shlex.split(cmd)
        tshark = subprocess.Popen(args, stdout=subprocess.PIPE)
        for line in io.TextIOWrapper(tshark.stdout, encoding="utf-8"):
            print("test: %s" % line.rstrip())

    def run(self, iface):
        try:
            t = Thread(target=self.testTshark, args=(iface, ))
            t.daemon = True
            t.start()
            t.join()
        except KeyboardInterrupt:
            print("\nExiting ARP monitor...")
            sys.exit(0)

if __name__ == '__main__':
    iface = 'wlan1'
    arps = ARPSniffer()
    arps.run(iface)

以上适用于 Python 3:

$ python3 tmp.py 
Testing if tshark works. Using wlan1
Capturing on 'wlan1'
3 test:     1 0.000000000 192.30.253.124 → 192.168.1.14 TLSv1.2 97 Application Data
test:     2 0.000264000 192.168.1.14 → 192.30.253.124 TLSv1.2 101 Application Data
test:     3 0.097729614 192.30.253.124 → 192.168.1.14 TCP 66 443 → 37756 [ACK] Seq=32 Ack=36 Win=38 Len=0 TSval=722975562 TSecr=2649326593