如何有效地分离不同大小的数据输入?

时间:2017-10-17 15:59:06

标签: python filter pcap organization

我正在尝试编写一个接收pcap文件的程序,通过应用程序tshark过滤数据包数据,并将数据输出到字典中,将各个数据包分开。我在分离部分遇到问题。

这基本上是我到目前为止所拥有的:

#example data input
records = ["Jamie,20,12/09/1997,Henry,15,05/12/2002,Harriot,22,11/02/1995"]

dict = {}
list1 = str(records).split(',')
i = 0
#seperates list into sublists with length "3"
list1 = [list1[i:i + 3] for i in range(0, len(list1), 3)] 

#places the sublists into a dictionary
for i in range (0,len(fields)): #places the sublists into dictionary
    dict[i] = list1[i][0].split(',') + list1[i][1].split(',') + list1[i][2].split(',')

print(dict)

输出如下:

{0: ["['Jamie", '20', '12/09/1997'], 1: ['Henry', '15', '05/12/2002'], 2: ['Harriot', '22', "11/02/1995']"]}

我理解我的代码是非常有缺陷和混乱的。为了存储从每一行获取更多数据,您需要手动将每个附加字段添加到字典中,同时必须更改分割列表的位置。任何关于如何更好地自动化这个过程的帮助,考虑到不同大小的输入,将不胜感激。如果我解释我的问题很差,请问。

编辑:这是我用来调用tshark的代码。前一代码的输入“out”转换为字符串。上一个示例中的姓名,年龄和出生日期代表ip源,ip目的地和协议。

filters = ["-e","ip.src"," -e ","ip.dst"," -e ","_ws.col.Protocol] #Specifies the metadeta to be extracted

tsharkCall = ["tshark.exe", "-r", inputpcap, "-T", "fields", filters]
tsharkProc = subprocess.Popen(tsharkCall, stdout=subprocess.PIPE)

out, err= tsharkProc.communicate()

1 个答案:

答案 0 :(得分:1)

考虑以下内容:

filters = ["ip.src","ip.dst","_ws.col.Protocol"] #Specifies the metadeta to be extracted
ex_base = 'tshark.exe -r {path} -Tfields {fields}'
ex = ex_base.format(path=myfile, fields=' '.join('-e ' + f for f in filters))
tsharkProc = subprocess.Popen(ex.split(), stdout=subprocess.PIPE, universal_newlines=True)

out, err= tsharkProc.communicate()

split_records = [line.split('\t') for line in out.split('\n')]
records = [dict(zip(filters, line)) for line in split_records]

# [{'ip.src': '127.0.0.1', 'ip.dst': '192.168.0.1', '_ws.col.Protocol': 'something'}, {...}, ...]

这假定您保留默认输出分隔符,即字段之间的记录和制表符之间的换行符。通过将字段数组压缩到输出记录,您将自动扩展字典以适应新字段,同时将它们添加到该数组中。

请注意,您也可以使用Pandas,以便优雅地解决此问题,例如:

import pandas as pd
records = pd.Dataframe(split_records, columns=filters)

这将为您提供一个可以使用的数据帧结构,根据您的应用程序,这可能很有用。