2017-10-17 63 views
3

我正試圖編寫一個程序,該程序需要一個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

試試'lst = records [0] .split(',')'。不要調用你的列表'list',因爲這是一個python內置的。但是目前,在分割它之前,您需要將1項目列表轉換爲其字符串表示形式。除此之外,我不確定你在問什麼。什麼是「田地」? – roganjosh

+0

你會總是有包含三行數據的字符串嗎?還是僅僅是這個例子? – scnerd

+0

有沒有什麼辦法可以爲每一行獲取不同的分隔符,比如'\ n'而不是'','? – scnerd

回答

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'}, {...}, ...] 

這假定您保留默認輸出分隔符,也就是記錄和標籤之間換行字段之間。通過將字段數組壓縮到輸出記錄中,您將自動擴展字典,以便在將新字段添加到該數組中時適應新字段。

注意,你也可以使用熊貓這樣完美地解決這個問題,比如:

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

這會給你一個數據幀結構的工作,這取決於你的應用程序,它可能是有用的。

+0

謝謝!我似乎無法讓壓縮部分工作,但我得到的錯誤「'字節'對象沒有屬性'讀'」。 –

+1

啊,對不起,我沒有用過多的子過程,並假設'溝通'返回的流。我更新了我懷疑應該解決問題的答案 – scnerd

相關問題