终止后从 tcpdump 子进程获取标准输出

编程入门 行业动态 更新时间:2024-10-15 22:26:03
本文介绍了终止后从 tcpdump 子进程获取标准输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我在这样的子进程中运行 tcpdump:

I am running tcpdump in a subprocess like this:

pcap_process = subprocess.Popen(['tcpdump', '-s 0', '-w -', 'tcp'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)

-w - 参数很重要:它告诉 tcpdump 将生成的 .pcap 文件打印到 stdout.

The -w - argument is important: it tells tcpdump to print the resulting .pcap file to stdout.

然后我继续使用 urllib.open() 访问网站.完成后,我想杀死 tcpdump 并将它打印的任何内容放入字符串中.我尝试了以下方法:

I then go on to access a website using urllib.open(). After this is done, I would like to kill tcpdump and put whatever it printed into a string. I have tried the following:

pcap_process.terminate() result = pcap_process.stdout.read() # or readline(), etc.

但是(除非我做错了什么),那是行不通的;我杀了这个进程,现在没有什么可读的了.如果我在终止之前使用 read() 或 communicate(),我的脚本将只是坐在那里继续阅读,等待 tcpdump完成(它不会).

But (unless I'm doing something wrong), that doesn't work; I killed the process, now there's nothing left to be read. If I use read() or communicate() before terminating, my script will just sit there and read on and on, waiting for tcpdump to finish (which it won't).

有没有办法做到这一点(最好没有循环)?

Is there a way to do this (preferably without loops)?

推荐答案

通常建议使用 PCAP 直接,或Scapy.

如果这不是一个选项,只需在 terminate 之后调用 communicate - 终止进程不会终止管道中的数据.但是,不要忘记在创建子流程时将参数分开([,'-w', '-'] 而不是 [... , '-w -',..]):

If that isn't an option, simply call communicate after terminate - killing a process does not kill data in the pipes to it. However, don't forget to separate arguments in the creation of the subprocess ([,'-w', '-'] instead of [... , '-w -', ..]):

pcap_process = subprocess.Popen(['tcpdump', '-s', '0', '-w', '-', 'tcp'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)

更多推荐

终止后从 tcpdump 子进程获取标准输出

本文发布于:2023-08-05 02:06:54,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1301658.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:进程   标准   tcpdump

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!