使用正则表达式使用netstat -nb python来匹配进程的名称

时间:2018-06-23 09:32:09

标签: regex python-3.x networking netstat

我正在使用python 3并尝试使用netstat -nb获取进程的名称。 我设法在子进程中使用了以下字符串:

  

'TCP 192.168.1.22:65477 212.55.188.116:443已建立\ n [WinStore.App.exe]'

我的问题是,如何使用正则表达式获取进程“ WinStore.App.exe”的名称。

3 个答案:

答案 0 :(得分:1)

您可以使用

\[([^\[\]]+)\]

并使用第一组。参见a demo on regex101.com


Python中:

import re

string = ' TCP 192.168.1.22:65477 212.55.188.116:443 ESTABLISHED\n [WinStore.App.exe]'

rx = re.compile(r'\[([^\[\]]+)\]')

apps = [m.group(1) for m in rx.finditer(string)]
print(apps)

这产生

['WinStore.App.exe']

答案 1 :(得分:0)

@Yuval 我没有在本地安装net stat软件包,但是我很确定提取进程名称的逻辑已成功运行,如屏幕快照所示。 我已经在regex101上进行了测试。

enter image description here

答案 2 :(得分:0)

这是一种方法。它假定您的输入字符串中没有〜字符,并且在方括号之前假定不超过200个字符,在方括号中假定不超过99个字符,并且在方括号之后不超过200个字符

    str = ' TCP 192.168.1.22:65477 212.55.188.116:443 ESTABLISHED\n [WinStore.App.exe]'
    newstr = re.sub("^[^~]{0,200}\[([^~]{0,99})\][^~]{0,200}$" ,  r"\1",    str     )