gpt4 book ai didi

python - Tshark 不通过 subprocess.Popen 执行

转载 作者:太空宇宙 更新时间:2023-11-04 00:23:24 25 4
gpt4 key购买 nike

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

关于python - Tshark 不通过 subprocess.Popen 执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48355172/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com