You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

通过subprocess.Popen调用Tshark无响应问题排查求助

问题:Python调用Tshark进程未启动的排查

问题描述

我尝试通过如下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运行程序,请问问题出在哪里?


问题排查与修复

你的代码里有两个关键问题,咱们逐一拆解:

1. 线程等待方法未实际调用

你在run方法里写的是t.join——这只是引用了方法对象,没有真正执行等待操作!正确写法应该是t.join()。

因为你设置了t.daemon = True(守护线程),主线程一旦结束,守护线程会立刻被终止。主线程执行到t.join(未调用)后直接结束,导致testTshark线程刚启动就被杀死,Tshark进程还没来得及真正启动就被终止了。

2. 未捕获Tshark的错误输出

Tshark可能因为权限、接口有效性或参数问题启动失败,但你的代码只捕获了标准输出,错误信息被完全吞掉,导致你看不到具体问题。

修改后的代码示例

import shlex
import subprocess
import io
import threading
import sys

class ARPSniffer:
    def testTshark(self, iface):
        print("Testing if tshark works. Using {}".format(iface))
        cmd = "tshark -i " + iface
        args = shlex.split(cmd)
        # 合并stdout和stderr,方便查看所有输出
        tshark = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True)
        # 用text=True直接按文本读取,无需手动包装TextIOWrapper
        for line in tshark.stdout:
            print(line.strip())
        # 获取进程返回码,排查启动失败原因
        return_code = tshark.wait()
        if return_code != 0:
            print(f"Tshark exited with error code: {return_code}")

    def run(self, iface):
        try:
            t = threading.Thread(target=self.testTshark, args=(iface, ))
            t.daemon = True
            t.start()
            # 调用join方法,等待线程执行完成
            t.join()
        except KeyboardInterrupt:
            print("\nExiting ARP monitor...")
            sys.exit(0)

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

额外排查建议

  • 先在终端手动执行sudo tshark -i wlan1,确认Tshark本身能正常启动抓包,排除接口异常或Tshark安装问题。
  • 如果手动执行也卡住,试试添加-n参数禁用名称解析,避免因DNS查询导致进程挂起。

内容的提问来源于stack exchange,提问作者EB-

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 08:43:10