如何解析子进程的结果

时间:2015-12-22 19:29:52

标签: python parsing subprocess

我试图将从netstat获取的Python中的字符串传递给awk,以用于构建新对象。

任何线索为什么这不起作用?请原谅可怕的编码,我今天刚开始使用Python并尝试学习如何使用该语言。

class NetstatGenerator():

    def __init__(self):
    import subprocess
    self.results = subprocess.Popen("netstat -anbp tcp", shell=True, stdout=subprocess.PIPE).stdout.read()
    self.list = []
    self.parse_results()

def parse_results(self):
    lines = self.results.splitlines(True)
    for line in lines:
        if not str(line).startswith("tcp"):
            print("Skipping")
            continue

        line_data = line.split(" ")
        self.list.append(NetstatData(self.line_data[0], self.line_data[15], self.line_data[18], self.line_data[23]))

def get_results(self):
    return self.list

class NetstatData():

    def __init__(self, protocol, local_address, foreign_address, state):
        self.protocol = protocol
        self.local_address = local_address
        self.foreign_address = foreign_address
        self.state = state

    def get_protocol(self):
        return str(self.protocol)

    def get_local_address(self):
        return str(self.local_address)

    def get_foreign_address(self):
        return str(self.foreign_address)

    def get_state(self):
        return str(self.state)

data = NetstatGenerator()

1 个答案:

答案 0 :(得分:2)

抱歉,netstat在Linux上不支持-b,而且我没有放置BSD框。

假设您有一个名为netstat_output的行列表,其中包含以下内容:

tcp 0 0 127.0.0.1:9557 127.0.0.1:56252 ESTABLISHED -

要解析单行,您split()并在索引0,3,4,5处选择元素。

要存储项目,您不需要定义样板保持类; namedtuple做你想做的事:

from collections import namedtuple

NetstatInfo = namedtuple('NetstatInfo', 
    ['protocol', 'local_address', 'remote_address', 'state'])

现在你可以解析一行:

def parseLine(line):
  fields = line.split()
  if len(fields) == 7 and fields[0] in ('tcp', 'udp'):  
    # alter this condition to taste; 
    # remember that netstat injects column headers.
    # consider other checks, too.
    return NetstatInfo(fields[0], fields[3], fields[4], fields[5])
  # otherwise, this function implicitly returns None

现在必须有这样的事情:

result = []

for line in subprocess.Popen(...):
  item = parseLine(line)
    if line:  # parsed successfully
      result.append(line)

# now result is what you wanted; e.g. access result[0].remote_address
相关问题