2017-08-03 28 views
0

我正在嘗試編寫一個程序,其中使用用戶選擇的.pcap文件,計算文件中的數據包數量,並提取每個數據包的源IP地址。之後,我想製作一個垂直條形圖,每個IP地址有一個不同的條形,每個條形的高度等於該IP地址作爲源的數據包數量。 (所以如果從10.2.82.5開始有3個數據包,將會有一個標記爲10.2.82.5的高度爲3的小節)。如何從pcap文件信息製作圖形

大概我會使用一個列表來包含數據,但我不知道如何增加數據來查找每個地址欄的高度。

我使用mcsp.wartburg.edu/zelle/python的圖形模塊,我想使用Scapy來提取源IP地址信息。

+0

我建議你使用像[Pygal](http://pygal.org/)這樣的包來創建圖表。但是,也許這需要你太多 - 我不知道你對Python有多熟悉。 – Gandaro

回答

0

使用Python的collections.Counter

給它一個所有IP地址的列表。它將返回一個可以類似於字典使用的對象(閱讀文檔)。密鑰將是IP地址;這些值將是這些IP地址的出現次數。

>>> import collections 
>>> addresses = ['127.0.0.1', '127.0.0.1', '8.8.8.8', '92.12.32.3'] 
>>> collections.Counter(addresses) 
Counter({'127.0.0.1': 2, '92.12.32.3': 1, '8.8.8.8': 1}) 
+0

謝謝你的建議 - 我已經實現了它,並與其他代碼段一起成功完成了此任務。 – soonhee

0

對於任何人好奇或處理類似的問題,這是我最後的(工作)代碼:

from graphics import * 
 
from scapy.all import * 
 
from collections import Counter 
 

 
def main(): 
 
filename = str(raw_input("What is the name of the file? ")) 
 

 
# sets packet source IPAs to sources, sourcenum also has # of occurrences 
 
IP.payload_guess = [] 
 
sources = list((p[IP].src) for p in PcapReader(filename) if IP in p) 
 
sourcenum = collections.Counter(sources) 
 
print sourcenum 
 

 
def makegraph(): 
 
    howmany = sum(1 for x in sourcenum.values()) 
 
    width = 1000/howmany 
 

 
    # creates graph window with white background 
 
    win = GraphWin("Packets Sent From Certain Addresses", 1080, 360) 
 
    win.setBackground("white") 
 
    Line(Point(80, 330), Point(1080, 330)).draw(win) 
 
    Line(Point(80, 0), Point(80, 330)).draw(win) 
 

 
    # creates y axis labels 
 
    Text(Point(40, 330), " 0k pkts").draw(win) 
 
    Text(Point(40, 280), " 3k pkts").draw(win) 
 
    Text(Point(40, 230), " 6k pkts").draw(win) 
 
    Text(Point(40, 180), " 9k pkts").draw(win) 
 
    Text(Point(40, 130), " 12k pkts").draw(win) 
 
    Text(Point(40, 80), " 15k pkts").draw(win) 
 
    Text(Point(40, 30), " 18k+ pkts").draw(win) 
 

 
    # create text and bar for each IPA 
 
    a = 80 
 
    subaddr = 1   
 
    for ipa in sourcenum: 
 
     whooheight = sourcenum.get(str(ipa)) \t \t \t 
 
     hooheight = whooheight/(18000/292) 
 
     hoheight = 330-hooheight 
 
     print hoheight \t   
 

 
     if hoheight >= 30: 
 
      hoopyheight = hoheight 
 
     else: 
 
      hoopyheight = 30 
 

 
     bar = Rectangle(Point(a, 330), Point(a + width, hoopyheight)) 
 
     bar.setFill("blue") 
 
     bar.draw(win) 
 
     Text(Point(a + width/2, 345), ipa).draw(win) 
 
     Text(Point(a + width/2, hoopyheight-15), str(whooheight) + " packets").draw(win) 
 
     a += width 
 

 
    raw_input("Press <Enter> to quit") 
 
    win.close() 
 

 
    makegraph() 
 

 
if __name__ == "__main__": 
 
main()

而且我使用Python 2.7版與Scapy的和圖形沿在最初的問題中提到的模塊。