drain3学习笔记

介绍

由于众所周知的原因,Github访问不稳定。官网虽然介绍,但是案例连接无效,因此保存于此,方便参考学习。

配置

官网样例(GitHub)

drain3.ini

[SNAPSHOT]
snapshot_interval_minutes = 10
compress_state = True[MASKING]
masking = [{"regex_pattern":"((?<=[^A-Za-z0-9])|^)(([0-9a-f]{2,}:){3,}([0-9a-f]{2,}))((?=[^A-Za-z0-9])|$)", "mask_with": "ID"},{"regex_pattern":"((?<=[^A-Za-z0-9])|^)(\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3})((?=[^A-Za-z0-9])|$)", "mask_with": "IP"},{"regex_pattern":"((?<=[^A-Za-z0-9])|^)([0-9a-f]{6,} ?){3,}((?=[^A-Za-z0-9])|$)", "mask_with": "SEQ"},{"regex_pattern":"((?<=[^A-Za-z0-9])|^)([0-9A-F]{4} ?){4,}((?=[^A-Za-z0-9])|$)", "mask_with": "SEQ"},{"regex_pattern":"((?<=[^A-Za-z0-9])|^)(0x[a-f0-9A-F]+)((?=[^A-Za-z0-9])|$)", "mask_with": "HEX"},{"regex_pattern":"((?<=[^A-Za-z0-9])|^)([\\-\\+]?\\d+)((?=[^A-Za-z0-9])|$)", "mask_with": "NUM"},{"regex_pattern":"(?<=executed cmd )(\".+?\")", "mask_with": "CMD"}]
mask_prefix = <:
mask_suffix = :>[DRAIN]
# engine is Optional parameter. Engine will be "Drain" if the engine argument is not specified.
# engine has two options: 'Drain' and 'JaccardDrain'.
# engine = Drain
sim_th = 0.4
depth = 4
max_children = 100
max_clusters = 1024
extra_delimiters = ["_"][PROFILING]
enabled = True
report_sec = 30

案例(GitHub)

简单案例

from drain3.drain import Drain, LogClustermodel = Drain()
entries = str.splitlines("""Dec 10 07:07:38 LabSZ sshd[24206]: input_userauth_request: invalid user test9 [preauth]Dec 10 07:08:28 LabSZ sshd[24208]: input_userauth_request: invalid user webmaster [preauth]Dec 10 09:12:32 LabSZ sshd[24490]: Failed password for invalid user ftpuser from 0.0.0.0 port 62891 ssh2Dec 10 09:12:35 LabSZ sshd[24492]: Failed password for invalid user pi from 0.0.0.0 port 49289 ssh2Dec 10 09:12:44 LabSZ sshd[24501]: Failed password for invalid user ftpuser from 0.0.0.0 port 60836 ssh2Dec 10 07:28:03 LabSZ sshd[24245]: input_userauth_request: invalid user pgadmin [preauth]"""
)for entry in entries:cluster, change_type = model.add_log_message(entry)print(cluster.get_template())

输出结果

Dec 10 07:07:38 LabSZ sshd[24206]: input_userauth_request: invalid user test9 [preauth]
Dec 10 <*> LabSZ <*> input_userauth_request: invalid user <*> [preauth]
Dec 10 09:12:32 LabSZ sshd[24490]: Failed password for invalid user ftpuser from 0.0.0.0 port 62891 ssh2
Dec 10 <*> LabSZ <*> Failed password for invalid user <*> from 0.0.0.0 port <*> ssh2
Dec 10 <*> LabSZ <*> Failed password for invalid user <*> from 0.0.0.0 port <*> ssh2
Dec 10 <*> LabSZ <*> input_userauth_request: invalid user <*> [preauth]

官网案例1

drain_stdin_demo.py

import json
import logging
import sys
from os.path import dirnamefrom drain3 import TemplateMiner
from drain3.template_miner_config import TemplateMinerConfig# persistence_type = "NONE"
# persistence_type = "REDIS"
# persistence_type = "KAFKA"
persistence_type = "FILE"logger = logging.getLogger(__name__)
logging.basicConfig(stream=sys.stdout, level=logging.INFO, format='%(message)s')if persistence_type == "KAFKA":from drain3.kafka_persistence import KafkaPersistencepersistence = KafkaPersistence("drain3_state", bootstrap_servers="localhost:9092")elif persistence_type == "FILE":from drain3.file_persistence import FilePersistencepersistence = FilePersistence("drain3_state.bin")elif persistence_type == "REDIS":from drain3.redis_persistence import RedisPersistencepersistence = RedisPersistence(redis_host='',redis_port=25061,redis_db=0,redis_pass='',is_ssl=True,redis_key="drain3_state_key")
else:persistence = Noneconfig = TemplateMinerConfig()
config.load(f"{dirname(__file__)}/drain3.ini")
config.profiling_enabled = Falsetemplate_miner = TemplateMiner(persistence, config)
print(f"Drain3 started with '{persistence_type}' persistence")
print(f"{len(config.masking_instructions)} masking instructions are in use")
print(f"Starting training mode. Reading from std-in ('q' to finish)")
while True:log_line = input("> ")if log_line == 'q':breakresult = template_miner.add_log_message(log_line)result_json = json.dumps(result)print(result_json)template = result["template_mined"]params = template_miner.extract_parameters(template, log_line)print(f"Parameters: {str(params)}")print("Training done. Mined clusters:")
for cluster in template_miner.drain.clusters:print(cluster)print(f"Starting inference mode, matching to pre-trained clusters. Input log lines or 'q' to finish")
while True:log_line = input("> ")if log_line == 'q':breakcluster = template_miner.match(log_line)if cluster is None:print(f"No match found")else:template = cluster.get_template()print(f"Matched template #{cluster.cluster_id}: {template}")print(f"Parameters: {template_miner.get_parameter_list(template, log_line)}")

官网案例2

drain_bigfile_demo.py

import json
import logging
import os
import subprocess
import sys
import time
from os.path import dirnamefrom drain3 import TemplateMiner
from drain3.template_miner_config import TemplateMinerConfiglogger = logging.getLogger(__name__)
logging.basicConfig(stream=sys.stdout, level=logging.INFO, format='%(message)s')in_gz_file = "SSH.tar.gz"
in_log_file = "SSH.log"
if not os.path.isfile(in_log_file):logger.info(f"Downloading file {in_gz_file}")p = subprocess.Popen(f"curl https://zenodo.org/record/3227177/files/{in_gz_file} --output {in_gz_file}", shell=True)p.wait()logger.info(f"Extracting file {in_gz_file}")p = subprocess.Popen(f"tar -xvzf {in_gz_file}", shell=True)p.wait()config = TemplateMinerConfig()
config.load(f"{dirname(__file__)}/drain3.ini")
config.profiling_enabled = True
template_miner = TemplateMiner(config=config)line_count = 0with open(in_log_file) as f:lines = f.readlines()start_time = time.time()
batch_start_time = start_time
batch_size = 10000for line in lines:line = line.rstrip()line = line.partition(": ")[2]result = template_miner.add_log_message(line)line_count += 1if line_count % batch_size == 0:time_took = time.time() - batch_start_timerate = batch_size / time_tooklogger.info(f"Processing line: {line_count}, rate {rate:.1f} lines/sec, "f"{len(template_miner.drain.clusters)} clusters so far.")batch_start_time = time.time()if result["change_type"] != "none":result_json = json.dumps(result)logger.info(f"Input ({line_count}): {line}")logger.info(f"Result: {result_json}")time_took = time.time() - start_time
rate = line_count / time_took
logger.info(f"--- Done processing file in {time_took:.2f} sec. Total of {line_count} lines, rate {rate:.1f} lines/sec, "f"{len(template_miner.drain.clusters)} clusters")sorted_clusters = sorted(template_miner.drain.clusters, key=lambda it: it.size, reverse=True)
for cluster in sorted_clusters:logger.info(cluster)print("Prefix Tree:")
template_miner.drain.print_tree()template_miner.profiler.report(0)

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/832254.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

字符串循环左移

#include <iostream> #include <string> using namespace std;int main() {string s1, s2;getline(cin, s1);int n;cin >> n;if(n>s1.size()){nn-s1.size();s2 s1.substr(0, n);s1.erase(0, n);cout << s1s2;}else{// 提取s1的前n个字符到s2中s2 …

MyBatis 多表映射及动态语句

三、MyBatis多表映射 3.1 多表映射概念 多表查询结果映射思路 前面说明中&#xff0c;我全面梳理了单表的mybatis操作&#xff01;但是开发中更多的是多表查询需求&#xff0c;这种情况我们如何让进行处理&#xff1f;MyBatis 思想是&#xff1a;数据库不可能永远是你所想或…

金融行业专题|信托超融合架构转型与场景探索合集

文章包含 15 信托用户基于超融合实现私有云建设、平台云下迁、信创云转型、容器云探索等场景实践分享。下载《【核心业务篇】金融核心生产业务场景探索文章合集》、《【信创转型与架构升级篇】金融核心生产业务场景探索文章合集》、《【数据库与数据仓库篇】金融核心生产业务场…

编程入门(六)【Linux系统基础操作一】

读者大大们好呀&#xff01;&#xff01;!☀️☀️☀️ &#x1f525; 欢迎来到我的博客 &#x1f440;期待大大的关注哦❗️❗️❗️ &#x1f680;欢迎收看我的主页文章➡️寻至善的主页 文章目录 &#x1f525;前言&#x1f680;Linux操作系统介绍与环境准备Linux操作系统介…

Windows远程桌面实现之十四:实现AirPlay接收端,让苹果设备(iOS,iPad等)屏幕镜像到PC端

by fanxiushu 2024-05-04 转载或引用请注明原始作者。 这个课题已经持续了好几年&#xff0c;已经可以说是很长时间了。 实现的程序是 xdisp_virt&#xff0c; 可以去github下载使用:GitHub - fanxiushu/xdisp_virt: xfsredir file system 一开始是基于测试镜像驱动的目的随便开…

Vue前端环境准备

vue-cli Vue-cli是Vue官方提供的脚手架&#xff0c;用于快速生成一个Vue项目模板 提供功能&#xff1a; 统一的目录结构 本地调试 热部署 单元测试 集成打包上线 依赖环境&#xff1a;NodeJs 安装NodeJs与Vue-Cli 1、安装nodejs&#xff08;已经安装就不用了&#xff09; node-…

linux文本三剑客之grep

目录 1、三剑客特点和应用场景 2、三件客之grep 1) -v 参数使用示例&#xff1a; 1、三剑客特点和应用场景 命令特点场景grep过滤grep命令过滤速度最快sed替换&#xff0c;修改文件内容&#xff0c;取行 如果要进替换/修改文件内容 取出某个范围的内容&#xff08;从中午12.到…

【stomp 实战】spring websocket用户消息发送源码分析

这一节&#xff0c;我们学习用户消息是如何发送的。 消息的分类 spring websocket将消息分为两种&#xff0c;一种是给指定的用户发送&#xff08;用户消息&#xff09;&#xff0c;一种是广播消息&#xff0c;即给所有用户发送消息。那怎么区分这两种消息呢?那就是用前缀了…

我们说的数据分析,到底要分析些什么?

作者 Gam 本文为CDA志愿者投稿作品 “我们说数据分析&#xff0c;到底要分析些什么&#xff1f;” 数据分析这个话题自从进入人们的视线以来&#xff0c;这个话题就成为人们茶余饭后的谈资&#xff0c;但是一千个人眼中就有一千个哈姆雷特&#xff0c;就意味着每个人对数据分…

使用Photoshop压缩图片大小的4种方法

使用Photoshop压缩图片大小&#xff0c;一般可采用下面4种方法&#xff1a; 1.调整图片分辨率&#xff1a; 打开需要压缩的图片文件。 依次点击菜单栏中的“图像”>“图像大小”。 在弹出的对话框中&#xff0c;通过调整分辨率参数来减小文件大小。 2.降低图片品质&#…

什么是水经微图注册码?

水经微图&#xff08;以下简称“微图”&#xff09;注册码&#xff0c;是微图的一种授权方式。 什么是微图注册码&#xff1f; 注册码仅可授权一台电脑&#xff0c;绑定CPU和网卡&#xff0c;激活后不可更换电脑使用。 如果CPU或网卡被更换&#xff0c;以及电脑损坏无法开机…

数据库中索引的底层原理和SQL优化

文章目录 关于索引B 树的特点MySQL 为什么使用 B 树&#xff1f; 索引分类聚簇索引 和 非聚簇索引覆盖索引索引的最左匹配原则索引与NULL索引的代价大表结构修改 SQL优化EXPLAIN命令选择索引列其它细节 关于索引 索引是一种用来加快查找效率的数据结构&#xff0c;可以简单粗暴…

卸载、安装、配置快捷mysql

卸载mysql 1、筛选过滤出mysql相关组件 rpm -qa | grep mysql2、关闭MySQL服务 systemctl stop mysql.service 3、卸载对应组件命令如下&#xff1a; rpm -ev --nodeps [显示的组件名称] 4、查找MySQL对应的所有文件夹 find / -name mysql rm -rf [显示的文件夹路径] 检查…

基于若依框架搭建网站的开发日志(一):若依框架搭建、启动、部署

RuoYi&#xff08;基于SpringBoot开发的轻量级Java快速开发框架&#xff09; 链接&#xff1a;开源地址 若依是一款开源的基于VueSpringCloud的微服务后台管理系统&#xff08;也有SpringBoot版本&#xff09;&#xff0c;集成了用户管理、权限管理、定时任务、前端表单生成等…

linux的基础入门(2)

环境变量 在Shell中&#xff0c;正确的赋值语法是没有空格的&#xff0c;即变量名数值。所以&#xff0c;正确的方式是&#xff1a; tmpshy 这样就将变量tmp赋值为"shy"了。 注意&#xff1a;并不是任何形式的变量名都是可用的&#xff0c;变量名只能是英文字母、…

【neteq】tgcall的调用、neteq的创建及接收侧ReceiveStatisticsImpl统计

G:\CDN\P2P-DEV\Libraries\tg_owt\src\call\call.cc基本是按照原生webrtc的来的:G:\CDN\P2P-DEV\tdesktop-offical\Telegram\ThirdParty\tgcalls\tgcalls\group\GroupInstanceCustomImpl.cpptg对neteq的使用 worker 线程创建call Call的config需要neteqfactory Call::CreateAu…

Java中使用RediSearch进行高效数据检索

RediSearch是一款构建在Redis上的搜索引擎&#xff0c;它为Redis数据库提供了全文搜索、排序、过滤和聚合等高级查询功能。通过RediSearch&#xff0c;开发者能够在Redis中实现复杂的数据搜索需求&#xff0c;而无需依赖外部搜索引擎。本文将介绍如何在Java应用中集成并使用Red…

300V直流充电桩测试有哪些实验项目

300V直流充电桩测试的实验项目主要包括以下几个方面&#xff1a; 1. 电气性能测试&#xff1a; - 输入电压范围测试&#xff1a;检查充电桩在不同输入电压下的正常工作情况。 - 输出电压范围测试&#xff1a;检查充电桩在不同输出电压下的正常工作情况。 - 输出电流范围测试…

MySQL#MySql数据库的操作

目录 一、创建数据库 二、字符集和校验规则 1.查看系统默认字符集以及校验规则 2.查看数据库支持的字符集 3.查看数据库支持的字符集校验规则 4.校验规则对数据库的影响 1.以UTF-8格式创建数据库 2.不区分大小写 3.区分大小写 4 大小写对数据库的影响 三、操纵数据…