如何从pcap文件信息制作图表

时间:2017-08-03 14:58:12

标签: python python-2.7 scapy

我正在尝试编写一个程序,其中我使用用户选择的.pcap文件,计算文件中的数据包数量,并提取每个数据包的源IP地址。之后,我想制作一个垂直条形图,每个IP地址都有一个不同的条形图,每个条形图的高度相当于以该IP地址为源的数据包的数量。 (如果有来自10.2.82.5的3个数据包,则会有一个标记为10.2.82.5且高度为3的条。)

据推测,我会使用一个列表来包含数据,但我不知道如何增加数据以找到每个地址'bar的高度。

我正在使用mcsp.wartburg.edu/zelle/python中的图形模块,我想使用Scapy来提取源IP地址信息。

2 个答案:

答案 0 :(得分: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})

答案 1 :(得分: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))			
        hooheight = whooheight/(18000/292)
        hoheight = 330-hooheight
        print hoheight	        

        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和初始问题中提到的图形模块。

相关问题