网络流量分析

网络流量分析网络流量分析具体要求收集自己本机的网络流量数据(至少1小时)并进行数据显示。可用wireshark软件抓包网络流量大小的时序图,可按每半分钟、每分钟、每五分钟、每十分钟进行分别显示。流量协议类型直方图可设置过滤条件,显示指定协议数据包、显示时间段数据包、显示长度范围内的数据包提示:由于代码导入pyshark模块,注意wireshark安装路径为C盘programfils文件夹下,…

大家好,又见面了,我是你们的朋友全栈君。

网络流量分析

具体要求

  • 收集自己本机的网络流量数据(至少1小时)并进行数据显示。
  • 可用wireshark软件抓包
  • 网络流量大小的时序图,可按每半分钟、每分钟、每五分钟、每十分钟进行分别显示。
  • 流量协议类型直方图
  • 可设置过滤条件,显示指定协议数据包、显示时间段数据包、显示长度范围内的数据包
  • 提示:由于代码导入pyshark模块,注意wireshark安装路径为C盘programfils 文件夹下,否则无法运行。

具体思路

  • 要想对数据进行分析,首先要有数据,所以第一步要抓取数据
  • 抓取数据我所知道的有两种方法,第一种为通过代码进行抓取,然后保存在文件中进行读取,第二种通过wireshark等软件进行抓取,然后通过代码分析。
  • 前者更倾向于分析实时数据包,后者则耗时间比较少(具体根据需要选择)
  • 拿到数据包以后,在分析之前,我们要通过代码把数据包中的内容拿出来,我选择pyshark.FileCapture方法
  • 作图我选择导入matplotlib模块,作图会方便很多
  • 具体的分析过程是一些简单的选择结构(ps:不懂得可以看一下Python基础篇)

python代码实现

# -*- coding: utf-8 -*-
import pyshark
from scapy.all import *
import matplotlib.pyplot as plt

# 读取pcap文件
packets = pyshark.FileCapture("./net_package.pcap")


def protocal(packets):
    """
    制作流量协议类型直方图
    :param packets: 读取的pcap文件数据
    """
    # 新建空字典
    dict = {}
    for packet in packets:
        if packet.highest_layer not in dict.keys():
            dict[packet.highest_layer] = 1
        else:
            dict[packet.highest_layer] += 1
    # print(dict)
    keys = dict.keys()
    values = dict.values()
    plt.figure(figsize=(8, 20), dpi=80)
    plt.bar(keys, values)
    plt.xticks(rotation=45)
    plt.xlabel('protocal')
    plt.ylabel('amount')
    plt.title('the amounts of all protocals')
    plt.show()


# print(proto_sum)
def graph_size(packets):
    """
    作流量大小时序图
    :param packets: 读取的pcap文件数据
    """
    time_stamps = []
    print("正在统计中。。。")
    for packet in packets:
        # print(int(float(packet.sniff_timestamp)))
        time_stamps.append(int(float(packet.sniff_timestamp)))
    # print(time_stamps)
    print("统计完成!")
    d = int(float(input("请输入时间间隔(单位:分钟):")) * 60)
    # d = 30 #半分钟
    num_bins = (max(time_stamps) - min(time_stamps)) // d
    step = len(time_stamps) // num_bins
    time_labels = [time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(i)) for i in time_stamps[::step]]
    # 新建20*8英寸图形,分辨率为80
    plt.figure(figsize=(20, 8), dpi=80)
    # X轴分布数据以及num_bins条柱状图
    plt.hist(time_stamps, num_bins)
    # 标签旋转角度45
    plt.xticks(range(min(time_stamps), max(time_stamps) + d, d), time_labels, rotation=45)
    # plt.xticks(range(min(time_stamps),max(time_stamps)+d,d),rotation = 45)
    plt.xlabel("timestamp")
    plt.ylabel("amount")
    plt.title("amount of per " + str(d) + " s")
    plt.show()


def filter(packets):
    """
    显示过滤器
    :param packets: 读取的pcap文件数据
    """

    protocal = input("请输入协议类型:")
    begin_time = input("请输入开始时间(Example:2019-09-09 10:58:42):")
    end_time = input("请输入结束时间(Example:2019-09-09 11:40:00):")
    length = int(input("请输入最大长度限制(单位:字节):"))
    # time.strptime把固定格式时间转换为时间元组
    array_begin_time = time.strptime(begin_time, "%Y-%m-%d %H:%M:%S")
    # time.mktime把时间元组转换为以秒表示的时间
    begin_time_stamp = float(time.mktime(array_begin_time))
    # print("begin_time_stamp:"+str(begin_time_stamp))
    array_end_time = time.strptime(end_time, "%Y-%m-%d %H:%M:%S")
    end_time_stamp = float(time.mktime(array_end_time))
    # print("end_time_stamp:"+str(end_time_stamp))
    packlist = []
    for packet in packets:
        # sniff_timestamp获取开始嗅探的时间戳
        time_stamp = float(packet.sniff_timestamp)
        # 获取数据包的捕获长度
        size = float(packet.captured_length)
        if packet.highest_layer == protocal and time_stamp > begin_time_stamp and time_stamp < end_time_stamp and size <= length:
            print(packet)
            packlist.append(packet)
    print("过滤出的数据包个数为 %s" % len(packlist))


# 调用函数进行操作

protocal(packets)
graph_size(packets)
filter(packets)


  • 需要提前抓好数据包,在代码中进行读取,然后进行分析。
  • 由于数据包较大,程序运行时间可能较长。

运行结果展示

  • 流量协议类型直方图
    在这里插入图片描述

  • 作流量大小时序图
    在这里插入图片描述
    在这里插入图片描述

  • 过滤器
  • 按照控制台提示输入过滤条件
    在这里插入图片描述

  • 最后会输出符合条件的数据包数量
    在这里插入图片描述
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/130923.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • MacBook —— 修改host文件「建议收藏」

    MacBook —— 修改host文件「建议收藏」文章目录MacBook——修改host文件MacBook——修改host文件打开Finder输入快捷键打开Finder输入快捷键Command+Shift+G,在弹出框中输入/etc/hosts:点击“前往”:打开hosts文件(用文本编辑即可)修改会出现没有权限的提示,我们点击“复制”然后修改完内容,将文件拷贝回这个地址,试图覆盖它,系统会出现下面的…

    2022年10月12日
    3
  • query did not return a unique_json.parsearray(string,class)

    query did not return a unique_json.parsearray(string,class)query.uniqueResult()和query.getSingleResult()当我使用query.getSingleResult()返回实例时,提示有错,不知道什么原因。按提示修改后还是有错后来使用query.uniqueResult()方法解决问题。publicstaticDepartmentgetDepartment(Sessionsession,Strin

    2022年9月28日
    2
  • eclipseUML工具

    eclipseUML工具
    EclipseUML2008-05-0522:05
    来源:lhttp://bach.yo2.cn/articles/category/artoftechnology/page/3
    对于UML工具,我用的并不是太深入,所以仅是对几款小型umltools,以及非专业umltools稍做评价,像RationalRose这种专业uml软件就不比较了。
     
    在选择方面个人比较偏向java,eclipse,逆向工程功能.
    1.MicrosoftVi

    2022年7月12日
    15
  • vue-property-decorator的简单介绍,一看就会

    vue-property-decorator的简单介绍,一看就会identifier!如果编译器不能够去除null或undefined,你可以使用类型断言手动去除。语法是添加!后缀:identifier!从identifier的类型里去除了null和undefined:functionfixed(name:string|null):string{functionpostfix(epithet:string){…

    2025年8月15日
    4
  • 移动硬盘格式导致无法copy大文件

    移动硬盘格式导致无法copy大文件

    2022年3月8日
    43
  • sql注入攻击属于什么攻击_ssr怎么用

    sql注入攻击属于什么攻击_ssr怎么用学好网络安全,以己之矛护己之盾

    2022年8月16日
    6

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号