Tshark没有通过subprocess.Popen执行

时间:2018-01-20 10:47:22

标签: python python-3.x subprocess popen tshark

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

<TextView
  android:id="@+id/text1"
  android:layout_width="match_parent"
  android:layout_height="100dp"
  android:text="first text"
  android:layout_margin="10dp"/>

打印“测试tshark是否有效。使用wlan1”但tshark无法启动。我使用top检查它,并且没有任何进程在运行。我究竟做错了什么?我正在使用sudo运行它。

谢谢大家。

1 个答案:

答案 0 :(得分:2)

@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