Day 6:连接数据之源 —— Splunk SDK for Python 实战


🚀 Day 6: 连接数据之源 ------ Splunk SDK for Python 实战

今日目标 : 验证Splunk 中的Python语句执行功能,包括调取插件参数,以及用SPL语句执行查询。相和谐都是我们在后期需要的核心功能。今天我们将直接在 Add-on Builder (AOB) 强大的前端代码编辑器中,利用 Splunk SDK for Python 获取 session_key。动态读取用户配置的 Index,执行带有特定时间窗口的防超载随机抽样 SPL,拉取 5 条真实的底层日志。在 AOB 内完成测试无语法报错后,回到 Splunk 搜索栏进行最终的后台调度与日志验证。


🛠️ Step 1: 回到 AOB 的代码实验室 (告别终端)

我们今天全程在 Splunk 前端网页中操作。

详细操作路径:

  1. 登录 Splunk : 打开浏览器,输入你的 Splunk 地址(通常是 http://localhost:8000),输入管理员账号密码登录。
  2. 进入 AOB 应用 : 在 Splunk 首页左侧的 Apps(应用)列表中,找到并点击 Splunk Add-on Builder
  3. 打开项目 : 在 AOB 首页的"Created with Add-on Builder"列表中,找到我们之前创建的 PEAK-llm-analyzer 项目,点击它进入项目主页。
  4. 进入数据收集配置页 : 在项目主页的顶部导航栏,点击 Configure Data Collection(配置数据收集)。
  5. 编辑任务模板 : 在弹出的列表中,找到我们在 Day 4 创建的 PEAK AI Hunter。点击这行最右侧的 Edit(编辑)按钮。
  6. 直达代码编辑区 : 此时会弹出向导窗口,直接点击顶部的第三个标签页:Define & Test(定义与测试)。

此时,你左侧看到的是参数输入区,右侧是 AOB 自带的 Code Editor(代码编辑器)。


💻 Step 2: 注入 SDK 抽样逻辑 (Define & Test 页面)

在右侧的 Code Editor 中,我们需要做两处核心修改。

第一处:在文件最顶部导入 SDK 滚动到代码的第一行,在原有的 import 列表下方,加入 Splunk 官方 SDK 库绑定(AOB 环境已自带,无需安装):

python 复制代码
import os
import sys
import time
import datetime
import json
# NEW: Import Splunk SDK bindings
import splunklib.client as client
import splunklib.results as results

第二处:重写 collect_events 函数 向下滚动找到 def collect_events(helper, ew): 这一行。将其下方的代码完全替换为以下逻辑: ⚠️ 极客铁律: 代码注释与日志严格使用纯英文。

python 复制代码
def collect_events(helper, ew):
    """Implement your data collection logic here"""
    
    helper.log_info("PEAK AI Hunter started data collection cycle.")

    try:
        # 1. Robustly acquire the session_key from the modular input context
        session_key = getattr(helper, 'session_key', None)
        
        # Fallback for certain AOB versions: extract from internal input_definition
        if not session_key and hasattr(helper, '_input_definition'):
            session_key = getattr(helper._input_definition, 'metadata', {}).get('session_key')
            
        if not session_key:
            helper.log_error("Failed to acquire session_key from context.")
            return

        # 2. Connect to the Splunk service using the SDK
        service = client.Service(token=session_key)

        # 3. Dynamically hijack the user-selected Index
        # We read the index the user configured in the UI during Day 5
        target_index = helper.get_output_index() or "main"

        # 4. Construct the randomized baseline SPL with a specific time window
        # Geek Tip: We use `earliest=-24h` to limit the time window, and `head 10000` BEFORE `random()` to prevent timeouts.
        search_query = (
            f"search index={target_index} earliest=-24h latest=now "
            f"| head 10000 | eval rand_val=random() | sort 5 rand_val"
        )
        
        # 5. Use jobs.oneshot for fast, synchronous retrieval in JSON format
        kwargs_oneshot = {"output_mode": "json"}
        helper.log_info(f"Executing randomized oneshot SPL: {search_query}")
        
        oneshot_search_results = service.jobs.oneshot(search_query, **kwargs_oneshot)

        # 6. Parse the results using the SDK's built-in JSON reader
        reader = results.JSONResultsReader(oneshot_search_results)
        
        baseline_logs = []
        for result in reader:
            if isinstance(result, dict) and "_raw" in result:
                baseline_logs.append(result["_raw"])

        # 7. Log the extracted data length and print a sample to verify success
        if len(baseline_logs) > 0:
            helper.log_info(f"Successfully fetched {len(baseline_logs)} random raw logs from index '{target_index}'.")
            helper.log_info(f"Sample Random Log [1]: {baseline_logs[0][:200]}...")
        else:
            helper.log_warning(f"SPL executed successfully, but returned 0 events from index '{target_index}'.")

    except Exception as e:
        helper.log_error(f"Execution error occurred during Splunk SDK search: {str(e)}")

⚡ Step 3: 一键防崩测试与保存

AOB 的代码编辑器自带了一个极客友好的防崩溃测试功能。

详细操作路径:

  1. 在页面左侧的 Data input parameters 区域,随便填入必须填的参数(比如输入 SDK Test)。
  2. 点击页面右上角绿色的 Test 按钮。
  3. 立即向下滚动网页,查看编辑器底部的 Output (输出) 面板。

🎉 测试成功标志: 此时,AOB 会在后台静默运行你的代码。只要 Output 面板最后显示了一个绿色的 Done,并且没有弹出大段红色的报错代码(Traceback) ,这就证明你的 Python 语法完美无缺,且 SDK 成功向系统发起了查询! (注:AOB 引擎会将 helper.log_info 直接写入底层的真实日志文件,因此你在前端面板只会看到 Done,这是企业级规范。)

  1. 固化代码 (Save) ------ 极其重要 : 测试没报错后,必须 点击右上角绿色的 Save 按钮保存代码,然后关闭向导窗口。

🔍 Step 4: 全局验证 ------ 回到 Splunk 检索真正的样本数据

我们在 AOB 里验证了代码"不会崩",现在要去系统的最底层去验收我们抓取到的"战利品"。

  1. 点击左上角的 Splunk>enterprise 徽标返回 Splunk 首页。

  2. 进入 Search & Reporting(搜索与报表)应用。

  3. 我们的代码被调度器接管后,每隔 60 秒就会跑一次。在搜索框中输入以下极客搜索命令,去内部日志里抓取结果:

    spl 复制代码
    index=_internal "PEAK AI Hunter started data collection cycle" OR "Sample Random Log"
  4. 将时间范围调整为 Last 15 minutes,点击搜索。

🎉 终极成功标志: 你会看到不仅有"开始采集"的心跳日志,每隔 60 秒 还会稳定地输出一次 Successfully fetched 5 random raw logs...,并且紧跟着一条 Sample Random Log [1]: ...。由于我们加了 random() 函数,你会发现每次打印出来的样本内容都是不一样的!

这证明你写的代码不仅极其强壮,而且正在源源不断地为 AI 采集真实的、不同切面的随机数据样本!

明天(Day 7),我们将把这些动态抽取的真实随机日志,配合极其严酷的 System Prompt(系统提示词),正式发往大模型。让 AI 化身资深安全专家,它将观察这些正常的系统日志,并像黑客一样逆向思考,推测出系统可能遭受的攻击方式(进入真正的威胁狩猎模式)!

相关推荐
贵慜_Derek17 小时前
《从零实现 Agent 系统》连载 08|编排与工作流:从 Chat 到任务图
人工智能·设计模式·架构
TigerOne17 小时前
第8章 查询引擎——LLM交互的心脏
人工智能
TigerOne17 小时前
第7章 响应式终端UI
人工智能
liangdabiao17 小时前
【开源】GEO分析行动Skill - 从各方面改善目前的GEO
人工智能
私人珍藏库17 小时前
【Android】图片工具箱-免费开源图片处理软件
android·人工智能·app·工具·软件·多功能
人工智能AI技术17 小时前
Claude Code六种授权模式全解析:彻底解决AI编程弹窗打断与权限失控难题
人工智能
DataX_ruby8217 小时前
企业常用的数据中台是哪些?
大数据·人工智能·数据治理·数据中台
m沐沐17 小时前
机器学习零基础吃透混淆矩阵!准确率 / 精确率 / 召回率 / F1 分数
人工智能·深度学习·机器学习·矩阵·pycharm