Title

【寒假作业三】——高级代码拼接工人的养成(改)

寒假作业二——高级代码技工的养成

什么样的CSDN孕育
什么样的码农
码农:我们不生产代码
我们只是CSDN的搬运工

Github 链接

戳我

对完成本次任务的初步预估

完成,这辈子是不可能完成的。 ——人类精神领袖窃格瓦拉

学习的语言

  • python(pythonyyds)
  • html(没有用到,但还是有了解一点)

算法

  • 在对题目要求的每k流量的处理时,我采用了这样的做法
  • flow_relation_bag_total_sum[cnt_flow//1000+1]=cnt_bags

遇到的困难与解决方式

遇到的困难

  • 太多了(不会抓包,抓包的时候被各种博客卡脖子,网络知识零基础,pyecharts调位置参数)

解决的方式

  • 问小白马
  • 默念小白马
  • 再问问小白马
  • B站,csdn ,奔向大佬的怀抱

学习资源

画图模板(flask)

from flask import Flask

from jinja2 import Markup
from pyecharts import options as opts
from pyecharts.charts import Bar,Grid,Pie,Line
app = Flask(__name__, static_folder="templates")
def grid_base() -> Grid():

     return "要返回的图表类型"
@app.route("/")
def index():
  c = grid_base()#调用函数并接收图表
  return Markup(c.render_embed())


#控制中心
if __name__ == "__main__":
  app.run(port=60)

折线图模板

  折线图变量名 = (
    Line()
    .add_xaxis(x轴列表)
    .add_yaxis(
        series_name="系列名字",
        y_axis=y轴列表,
        )
  )

双y轴一直搞不出来。。

总结以及实际用时

  • 做前抚膺叹息,做时胜似蹲监,做完感觉良好,
  • 自闭一个礼拜(调节:观看《山海情》)
  • 启动三天
  • 画画四天(摸鱼)

假装自己是老板

  • 问:如果你是竞争对手,能否找到其他进攻方式绕开该规则,或者通过其他网络手段有效打击对手?(请勿模仿)
  • 答:定期更改自己发送时用的源地址(不包括端口)或源地址端口
  • 问:这些懒懒的技术人员制定的判定规则会出现的问题有哪些?
  • 答:可能把正常的地址也标记成异常了(就好像一款杀毒软件对检测到的东西全标记为进行攻击,或者像辐射把正常细胞也当成癌细胞进行攻击)
  • 问:评估自己的系统的处理效率
  • 答:感觉良好
  • 问:老板某日在想桃子:我xxx有一个梦想,建成世界一流 news app!能够为世界上每个网民提供吃瓜服务。请从多个方向考虑该系统需要改进的地方还有哪些?(数据量,效率,安全性等等)
  • 答:让子弹飞会

代码

# Author:Hugh

# -*- codeing = utf-8 -*-

# @Time : 2021/2/4 15:17
# @Author : Hugh
# @File : 寒假作业2.py
# @Software: PyCharm
from scapy.all import *
import re

from flask import Flask
from jinja2 import Markup
from pyecharts import options as opts
from pyecharts.charts import Bar,Grid,Pie,Line

#假控制台
control_time = 120
Φ = 300000  #包数
φ = 500000  #包长
#timeout参数用来控制抓包的周期
packet =sniff(timeout=control_time,prn=lambda x : x.sprintf("{IP:%IP.src%-> %IP.dst%}")) #抓包
p=wrpcap('lygg.pcap', packet) #存包
packets=rdpcap("lygg.pcap") #读包


cnt_udp = 0
cnt_tcp = 0
cnt_arp = 0
cnt_icmp = 0
cnt_igmp = 0
cnt_ospf = 0
cnt_other = 0
cnt_flow = 0
#
cnt_len = 0
cnt_bags = 0
cnt_success_bags = 0

five_tuple = {}   #建立五元组字典
flow_relation_bag_total_length = {}  #建立一个字典用来统计流的总长
flow_relation_bag_total_sum = {}   #建立一个字典用来统计流的总数
# 五元组提取区
for bag in packets:
    cnt_bags = cnt_bags + 1
    print("这是第{}个包".format(cnt_bags))
    flow_relation_bag_total_sum[cnt_flow//1000+1]=cnt_bags
    try:
        if (bag[1].proto == 6 or bag[1].proto == 17):
            PROTO = bag[1].proto
            Len= bag[1].len
            cnt_success_bags=cnt_success_bags+1
            cnt_len=cnt_len+Len
            flow_relation_bag_total_length[cnt_flow//1000+1] = cnt_len


            if (PROTO == 17):
                Proto = "UDP"
                cnt_udp = cnt_udp + 1
            else:
                Proto = "TCP"
                cnt_tcp = cnt_tcp + 1
            Src = bag[1].src
            Dst = bag[1].dst
            Sport = bag[1].sport
            Dport = bag[1].dport

            s = "{:}  \n Src : {}:{}\n   Dst : {}:{} \n Len : {}".format(Proto, Src, Sport, Dst, Dport, Len)
            if s not in five_tuple:
                five_tuple[s] = [0,Len]
                cnt_flow = cnt_flow + 1#流的数量加一
            else:
                five_tuple[s][0] = five_tuple[s][0] + 1
                five_tuple[s][1] = five_tuple[s][1] + Len
        else:
            if(bag[1].proto == 1):
                 cnt_icmp = cnt_icmp + 1
            elif(bag[1].proto == 2):
                 cnt_igmp = cnt_igmp + 1
            elif(bag[1].proto == 89):
                 cnt_ospf = cnt_ospf + 1
    except Exception as  e:
        try:
            if (bag[0].type == 2054):
                cnt_arp = cnt_arp + 1
            else:
                cnt_other = cnt_other + 1
        except Exception as e:
            cnt_other = cnt_other + 1

        # print(Five_Tuple)
# 协议:其中1,标识ICMP、2标识IGMP、6标识TCP、17标识UDP、89标识OSPF。
# data.payload.name:'IP','IPV6','ARP'或者其他

#绘图材料准备区
#1.柱状图区
##正则
#s = "{}  {}:{}   {}:{}".format(Proto, Src, Sport, Dst, Dport)
#pattern = re.compile(r'.*?([1-9][0-9]{0,2}.[1-9][0-9]{0,2}.[1-9][0-9]{0,2}.[1-9][0-9]{0,2}).*?')   # re.I 表示忽略大小写
def Creating_Bar_Source(Five_Tuple):
    xaxis = []
    yaxis = []
    for x,y in Five_Tuple.items():

        if y[0] > Φ or y[1] > φ:                 ##设置阈值
          #xsrc=pattern.match(x)
          #xaxis.append(xsrc.group(1))
          xaxis.append(x)
          yaxis.append(y[0])
    print(xaxis)
    print(yaxis)
    return xaxis,yaxis
#2.小bar图区
xaxis_small=['Φ','φ']
yaxis_small=[Φ,φ]
#3.玫瑰饼图区
proto_types=["UDP","TCP","ARP","ICMP","IGMP","OSPF","Other"]
proto_nums=[cnt_udp,cnt_tcp,cnt_arp,cnt_icmp,cnt_igmp,cnt_ospf,cnt_other]
zipped=zip(proto_types,proto_nums)
#4.折线区域
##flow_relation_bag_total_length
flow_len_x = []
flow_len_y = []
for lenx,leny in flow_relation_bag_total_length.items():
    flow_len_x.append(str(lenx)+'k')
    flow_len_y.append(leny)
##flow_relation_bag_total_sum
flow_cnt_x = []
flow_cnt_y = []
for cntx,cnty in flow_relation_bag_total_sum.items():
    flow_cnt_x.append(str(cntx)+'k')
    flow_cnt_y.append(cnty)
# 绘图区
app = Flask(__name__, static_folder="templates")  #建立一个Flask实例app程序
def grid_base() -> Grid():        #->起到一个修饰提醒的作用
  xaxis,yaxis =Creating_Bar_Source(five_tuple)

  bar_five = (
      Bar(init_opts=opts.InitOpts(width='60px', height='180px',bg_color="#654ea3"),)
          .add_xaxis(xaxis)
          .add_yaxis(
              series_name="count_five",
              y_axis=yaxis,
      )
          .set_global_opts(
                  title_opts=opts.TitleOpts(title="可疑流量探测器", subtitle="单词抓取时间周期为{}s".format(control_time),pos_top="1%",pos_left="1%"),
                  legend_opts=opts.LegendOpts(pos_top="6%",pos_left="1%"),
                  xaxis_opts=opts.AxisOpts(name="五元组(流)"),
                  yaxis_opts=opts.AxisOpts(name="五元组总数(流数)")

      )

          .set_series_opts(label_opts=opts.LabelOpts(is_show= True))

  )
  bar_threshold = (
      Bar(init_opts=opts.InitOpts(width='30px', height='60px'))
          .add_xaxis(xaxis_small)
          .add_yaxis("阈值大小", yaxis_small)
          .set_global_opts(
               title_opts=opts.TitleOpts(title="阈值表",pos_top="3%", pos_bottom='80%', pos_left='75%',pos_right="10%"),
               legend_opts=opts.LegendOpts(pos_top="7%", pos_bottom='80%', pos_left='75%',pos_right="10%"))

  )
  pie = (
         Pie(init_opts=opts.InitOpts(width="600px",height="300px"))#,is_label_show=True
         .add("", [list(z) for z in zipped],rosetype=True,radius=[40,90],center=["17%","80%"])
        # .set_colors(["blue", "green", "yellow", "pink"])
         .set_global_opts(title_opts=opts.TitleOpts(
             title="包种类比例",pos_top="50%",pos_bottom="60%",pos_left="1%"),
             legend_opts=opts.LegendOpts(pos_left="1%",pos_top="55%"))
         .set_series_opts(label_opts=opts.LabelOpts(formatter="{b}: {c}"))
  )

  #折线图
  line1 = (
    Line(init_opts=opts.InitOpts())
    .add_xaxis(flow_len_x)
    .add_yaxis(
        series_name="total_len",
        y_axis=flow_len_y,
        yaxis_index=0,
        label_opts=opts.LabelOpts(is_show=False),
        markpoint_opts=opts.MarkPointOpts(
            data=[opts.MarkPointItem(type_="max", name="最大值"),
                  opts.MarkPointItem(type_="min", name="最小值")]),
        areastyle_opts=opts.AreaStyleOpts(opacity=0.5)
        )
    .extend_axis(yaxis=opts.AxisOpts())
    .set_global_opts(
        title_opts=opts.TitleOpts(title="总包长和总包数与流量的关系", pos_top="50%", pos_left='50%'),
        legend_opts=opts.LegendOpts(pos_left="50%", pos_top="55%"),  #标签的位置
        xaxis_opts=opts.AxisOpts(name="总流量"),                     #给x轴贴名字
        yaxis_opts=opts.AxisOpts(name="数值"),                     #给y轴贴名字
                    )
    .set_series_opts(label_opts=opts.LabelOpts(is_show=False))
  )
  line2 = (
      Line()
      .add_xaxis(flow_len_x)
      .add_yaxis(
          series_name="total_bag_cnt",
          y_axis=flow_cnt_y,
          yaxis_index=1,
          areastyle_opts=opts.AreaStyleOpts(opacity=0.5),
          label_opts=opts.LabelOpts(is_show=False),
          markpoint_opts=opts.MarkPointOpts(
          data=[opts.MarkPointItem(type_="max", name="最大值"),
                opts.MarkPointItem(type_="min", name="最小值")])
      )
  )
  line1.overlap(line2) #图的叠加,但双y轴一直用不了
  #组合图
  grid = (
      Grid(init_opts=opts.InitOpts(width='1400px',height='1000px',bg_color="#f7b733"))#初始化宽度,高度和设置背景颜色
          #通过四个位置参数,给各种图分配位置
          .add(bar_five, grid_opts=opts.GridOpts(pos_top="11%",pos_bottom='60%',pos_right="25%"))
          .add(bar_threshold, grid_opts=opts.GridOpts(pos_top="10%", pos_bottom='80%', pos_left='80%',pos_right="10%"))
          .add(line1, grid_opts=opts.GridOpts(pos_top="60%",pos_bottom="10%",pos_left="50%"))
          .add(pie, grid_opts=opts.GridOpts(pos_bottom="10%",pos_left="10%",pos_top="85%",pos_right="90%"))
  )
  return grid
#flask模板,flask对象和index的连接(@起到对函数修饰的作用)
@app.route("/")
def index():
  c = grid_base()   # 返回一个Grid()实例
  return Markup(c.render_embed())


#控制中心
if __name__ == "__main__":
  app.run(port=60)

感谢

感谢小白马,xsgg,小o,lygg,卷神的指导!!!!

posted @ 2021-02-06 20:38  BeautifulWater  阅读(299)  评论(7编辑  收藏  举报