我正在尝试获取ngrep的输出并使用Python将其写入日志文件,同时还会拖尾日志文件.我在网上看过一些例子,但有些看起来过时而且过时了,其他人使用shell = True,这是不鼓励的.
在perl中我只使用类似于以下内容的东西
#!/usr/bin/perlopen(NGFH,"ngrep -iW byline $filter");while ($line = <NGFH>) { open(LOG,">> /path/to/file.log") // highlighting,filtering,other sub routine calls print LOG $line}
我已经开始工作,但ngrep没有.我想能够无限地运行它并在过滤后将流从ngrep输出到日志文件.我无法从ngrep获得输出以显示在stdout中,所以这就是我已经得到的.我希望能够在更新日志文件时看到数据文件尾部,并查看ngrep的输出.现在我只是使用bash运行以下内容.
echo "." >> /path/to/ngrep.log
谢谢!
这是我到目前为止所得到的……
更新
这似乎现在有效.我不知道如何改进它.
import subprocessimport selectimport relog = open('/path/to/ngrep.log','a+',0)print log.namen = subprocess.Popen(['ngrep','-iW','byline'],\ stdout=subprocess.PIPE,stderr=subprocess.STDOUT)p = select.poll()p.register(n.stdout)f = subprocess.Popen(['tail','-F','-n','0','/path/to/tailme.log'],stderr=subprocess.PIPE)p2 = select.poll()p2.register(f.stdout)def srtrepl(match): if match.group(0) == 'x.x.x.x': # do something if match.group(0) == 'x.x.y.y': # do something else return '3[92m'+ match.group(0) + '3[0m'while True: if p.poll(1): line = n.stdout.readline() s = re.compile(r'(8.8.(4.4|8.8)|192.168.[0-9]{1,3}.[0-9]{1,3})' ) print s.sub( srtrepl,line ) log.write(n.stdout.readline()) if p2.poll(1): print f.stdout.readline().rstrip('\n')解决方法 要在Python中模拟perl代码:
#!/usr/bin/env python3from subprocess import Popen,PIPEwith Popen("ngrep -iW byline".split() + [filter_],stdout=PIPE) as process,\ open('/path/to/file.log','ab') as log_file: for line in process.stdout: # read b'\n'-separated lines # highlighting,other function calls log_file.write(line)
它启动ngrep进程传递filter_变量并将输出附加到日志文件,同时允许您在Python中修改它.请参阅Python: read streaming input from subprocess.communicate()(可能存在缓冲问题:检查ngrep是否支持 – 像grep这样的–line-buffered选项,如果你想在post_file.write(line)之后拖尾file.log然后调用log001,或者调用log_file.flush()).
您也可以在纯Python中模拟ngrep.
如果你想同时读取几个进程的输出(在你的情况下为ngrep,tail),你需要能够read pipes without blocking e.g.,using threads,async.io.
总结以上是内存溢出为你收集整理的如何在python中生成另一个进程并捕获输出?全部内容,希望文章能够帮你解决如何在python中生成另一个进程并捕获输出?所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)