我正在尝试在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)


它显示“正在测试tshark是否有效。使用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

10-06 14:13