A caver in a red helmet searching a lamp-lit passage in Mammoth Cave, with the article title about generating Splunk SPL searches with an LLM
Cover based on a photo by National Park Service Digital Image Archives, via Wikimedia Commons, Public domain

You can generate Splunk SPL with an LLM in a few seconds, and the search will usually look like something a senior analyst wrote: index=, a stats with a by clause, a where threshold, maybe a tstats for speed. The problem is what happens next. Some drafts fail to parse. Worse, many parse, run, and return zero rows, and in a hunt "no results" looks exactly like "nothing happened." An LLM Splunk search is a draft until it has run against data where you already know the answer.

This guide runs that loop on a Splunk Enterprise 10.6.2.5 lab with 1,218 synthetic Windows-style security events, covering four hunts Splunk shops write constantly: failed logons by source, password spraying, a brute force that ends in a successful logon, and rare process launches. Every error message and every result table below is real output from that lab, captured with splunk search and Splunk's REST API on localhost. The drafts were written for this guide to reproduce mistakes models commonly make in SPL; they are not a captured model transcript, and no model was called in the lab.

If your team hunts in Microsoft Sentinel instead, our guide to KQL hunting queries with an LLM covers that language. For endpoint state rather than logs, see osquery queries with an LLM.

Authorized, defensive work only. Write and test searches on a Splunk instance and data you own or are explicitly allowed to work with. Keep real hostnames, usernames and IP addresses out of prompts unless you are cleared to share them; see what to send the model.

Why generate Splunk SPL with an LLM

SPL is easy to read and easy to get subtly wrong. A search is a pipeline: the first segment pulls events from an index, and each | hands rows to the next command. Models have seen a great deal of SPL, plus a great deal of KQL, SQL, Sigma and SPL2, and they blend them. That produces three kinds of failure:

  1. Syntax that doesn't exist. A command borrowed from another language, or an aggregate function used where only eval functions are allowed. Splunk rejects these, which is the good case.
  2. Field names that don't exist in your data. CIM-style names like src_ip and user only exist if an add-on or your own field aliases create them. Splunk doesn't complain about a missing field. The search runs and returns nothing.
  3. Logic that answers a different question. The search runs, returns rows, and misses the attack you were hunting for.

The model is good at the boring parts: turning "show me sources that failed against many accounts" into stats dc(), remembering strftime formats, and writing the eval for a readable table. Only your Splunk instance knows your field names, which fields are indexed, and what the data really looks like. So the loop matters more than the prompt.

The lab: Splunk 10.6 and 1,218 synthetic events

We downloaded the Splunk Enterprise 10.6.2.5 Linux tarball, checked it against Splunk's published SHA-512, and started it bound to 127.0.0.1 with Splunk Web turned off. One note if you follow older install guides: the --answers-yes flag they include was rejected in 10.6 (Bad Option --answers-yes), and splunkd didn't start. This worked:

./splunk start --accept-license --no-prompt --seed-passwd "$LAB_PASSWORD"
./splunk add index lab
./splunk add oneshot winsec_lab.json -index lab -sourcetype lab:winsec:json -host winsec-lab

The data is one JSON event per line, shaped like Windows Security events: 4624 successful logons, 4625 failed logons and 4688 process creation, using Microsoft's field names (TargetUserName, IpAddress, NewProcessName, ParentProcessName). A small Python script generated it with a fixed seed, using documentation IP ranges for anything external. The sourcetype extracts JSON at search time (KV_MODE = json), which is how many custom JSON sources are set up and matters later for tstats.

We planted four things to find, all on one day in September 2026:

Planted activityGround truth
Password spray203.0.113.45 fails once each against 25 accounts in under 8 minutes
Brute force, then success198.51.100.7 fails 30 times against svc-backup, then logs on
Download with a living-off-the-land binarycertutil.exe -urlcache launched by PowerShell on WS-114
Exfil tool from a public folderC:\Users\Public\rclone.exe launched by PowerShell on WS-114

Everything else is noise: 400 normal logons, 60 scattered typo failures from internal addresses, and 700 routine process launches.

Step 1: Give the model your real field names

Most bad SPL starts with a guessed field name, so start every prompt with the fields that actually exist. The fieldsummary command lists them:

index=lab sourcetype="lab:winsec:json"
| fieldsummary
| where count > 0 AND NOT match(field, "^(date_|time|punct|linecount|splunk_server)")
| table field count
      field       count
----------------- -----
CommandLine         702
Computer           1218
EventCode          1218
IpAddress           516
LogonType           516
NewProcessName      702
ParentProcessName   702
Status              115
SubStatus           115
SubjectUserName     702
TargetUserName      516
host               1218
index              1218
source             1218
sourcetype         1218

Paste that table into the prompt with the index and sourcetype. It's short, contains no event data, and removes the most common class of silent failure.

Step 2: Parse the draft before you run it

Here are three drafts of a "sources failing against many accounts" hunt, each with a mistake we see models make in SPL. Run through splunk search, all three failed before touching data:

index=lab EventCode=4625
| stats count dc(TargetUserName) as users by IpAddress
| filter users > 10
Unknown search command 'filter'.

filter isn't an SPL command. The model borrowed it from another query language. Filtering after stats is what where is for.

index=lab EventCode=4625
| stats count by IpAddress
| where dc(TargetUserName) > 10
FATAL: Error in 'where' command: The 'dc' function is unsupported or undefined.

dc() is a stats function, not an eval function, and by the time where runs, TargetUserName is gone anyway: stats count by IpAddress keeps only IpAddress and count. Compute the distinct count inside stats, name it, then filter on the name.

index=lab EventCode=4625 earliest="2026-09-22T00:00:00" latest="2026-09-23T00:00:00"
| stats count by IpAddress
FATAL: Invalid value "2026-09-22T00:00:00" for time term 'earliest'

ISO 8601 looks right, and it's what models reach for. SPL's absolute time format is %m/%d/%Y:%H:%M:%S, per Splunk's time modifiers page. Part of the confusion is real: the SPL2 time modifiers page shows %Y-%m-%d:%H:%M:%S, so tell the model which language you're writing. For SPL:

earliest="09/22/2026:00:00:00" latest="09/23/2026:00:00:00"

You don't need to run a search to catch these. Splunk's REST API has a parser endpoint, search/v2/parser (POST only; the older search/parser is listed as deprecated and disabled). Against the lab:

curl -sk -u admin:"$LAB_PASSWORD" https://127.0.0.1:8089/services/search/v2/parser \
  -d output_mode=json \
  --data-urlencode q='search index=lab EventCode=4625 | stats count dc(TargetUserName) as users by IpAddress | filter users > 10'
HTTP 400
[{"type": "FATAL", "text": "Unknown search command 'filter'."}]

The same call returned HTTP 400 with the exact dc and earliest messages above, and HTTP 200 with the parsed command list (search, stats, where) once the draft was fixed. That's a cheap first gate for every model draft.

Step 3: The searches that run and return nothing

The parser can't tell you a search is useless. These four drafts all parsed, all ran with exit code 0, and all returned nothing on data that contains the activity they're looking for.

Guessed field names. The spray and brute-force sources are both in the data, yet:

index=lab EventCode=4625
| stats count by src_ip, user
| where count > 10

returned zero rows and no warning. This data has IpAddress and TargetUserName; there is no src_ip or user. If your Windows data runs through an add-on that maps to CIM names, the CIM names may be right for you. That's exactly why Step 1 comes first.

tstats on a search-time field.

| tstats count where index=lab EventCode=4625 by IpAddress

Zero rows, no error. The tstats docs are explicit that it works on indexed fields in tsidx files, from indexed data or accelerated data models, and that its WHERE clause "must contain field-value pairs that are indexed." Our JSON fields are extracted at search time, so tstats can't see them. More on when tstats is the right call below.

Wildcards in where.

index=lab EventCode=4625
| where TargetUserName="svc-*"
| stats count by TargetUserName

Zero rows. In where, "svc-*" is a literal string comparison. The where docs say you can only use a wildcard there through the like function, with % as the wildcard:

index=lab EventCode=4625
| where like(TargetUserName, "svc-%")
| stats count by TargetUserName
TargetUserName count
-------------- -----
svc-backup        30

In the first search segment, TargetUserName="svc-*" works, because the search command does support *; in the lab it returned the same 30 svc-backup failures.

Windows paths without escaping.

index=lab EventCode=4688 NewProcessName="C:\Users\Public\*"
| table _time Computer NewProcessName
INFO: No matching fields exist.

The search command docs say backslash escape sequences are expanded inside quotation marks, and the backslash escapes itself. Double each one:

index=lab EventCode=4688 NewProcessName="C:\\Users\\Public\\*"
| table _time Computer SubjectUserName NewProcessName ParentProcessName
           _time            Computer SubjectUserName       NewProcessName                           ParentProcessName
--------------------------- -------- --------------- -------------------------- ---------------------------------------------------------
2026-09-22 14:04:37.000 PDT WS-114   dina            C:\Users\Public\rclone.exe C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe

One more that bites when you test on old or replayed data: a relative time like earliest=-24h is resolved against now. Our lab data is from September, so index=lab EventCode=4625 earliest=-24h | stats count by IpAddress correctly returned nothing. Use absolute times when you validate against a fixed dataset, and switch to relative times when you schedule the search.

Step 4: Fix the logic against planted answers

Once the field names are right, this draft runs and returns a row:

index=lab EventCode=4625
| stats count by IpAddress, TargetUserName
| where count > 10
 IpAddress   TargetUserName count
------------ -------------- -----
198.51.100.7 svc-backup        30

It found the brute force. It did not find the password spray, because a spray tries each account once or twice. Counting failures per source and user is a brute-force detector, not a spray detector. That's the kind of mistake a model makes when the prompt says "find password attacks," and it's why you plant both patterns. For spraying (MITRE ATT&CK T1110.003), count distinct accounts per source:

index=lab sourcetype="lab:winsec:json" EventCode=4625
    earliest="09/22/2026:00:00:00" latest="09/23/2026:00:00:00"
| stats count as failures dc(TargetUserName) as users min(_time) as first max(_time) as last by IpAddress
| where users >= 10
| eval minutes=round((last-first)/60, 1)
| fields IpAddress failures users minutes
 IpAddress   failures users minutes
------------ -------- ----- -------
203.0.113.45       25    25     7.7

The obvious next step is to add time windows with bin, so a slow spray across a week doesn't hide behind a daily total:

... | bin _time span=15m
| stats count as failures dc(TargetUserName) as users values(Computer) as targets by _time, IpAddress
| where users >= 10 | sort - users
           _time             IpAddress   failures users  targets
--------------------------- ------------ -------- ----- ---------
2026-09-22 02:00:00.000 PDT 203.0.113.45       14    14 SRV-APP02
2026-09-22 02:15:00.000 PDT 203.0.113.45       11    11 SRV-APP02

Look at what happened. The spray started at 02:10 and crossed the 02:15 bucket boundary, so the 25 accounts were split 14 and 11. With a threshold of 15 per bucket, this search would have missed the spray entirely. Fixed buckets cut events at clock boundaries, not at attack boundaries. Either set the threshold with that in mind, use a wider span than the behavior you're hunting, or run both a daily and a windowed version. The model won't point this out unless you ask, and you won't notice unless the planted answer is 25.

Brute force followed by a successful logon

Failed logons alone are noisy. Failures followed by a success from the same source on the same account are worth a page (T1110.001). The count(eval(...)) pattern from the stats docs counts both in one pass:

index=lab sourcetype="lab:winsec:json" EventCode IN (4624, 4625)
    earliest="09/22/2026:00:00:00" latest="09/23/2026:00:00:00"
| stats count(eval(EventCode=4625)) as failures count(eval(EventCode=4624)) as successes
        min(_time) as first_fail max(_time) as last_seen by IpAddress, TargetUserName
| where failures >= 10 AND successes > 0
| eval first_fail=strftime(first_fail, "%F %T"), last_seen=strftime(last_seen, "%F %T")
 IpAddress   TargetUserName failures successes     first_fail           last_seen
------------ -------------- -------- --------- ------------------- -------------------
198.51.100.7 svc-backup           30         1 2026-09-22 03:00:10 2026-09-22 03:05:40

This version doesn't check order: a success before the failures would also match. For a scheduled detection, add a check that the success came after the last failure, and confirm it with a planted case in which it didn't.

Rare processes: rare vs stats

The rare command is the first thing a model reaches for in a rare-process hunt:

index=lab EventCode=4688 | rare limit=5 NewProcessName
                      NewProcessName                        count  percent
----------------------------------------------------------- ----- ---------
C:\Users\Public\rclone.exe                                      1  0.142450
C:\Windows\System32\certutil.exe                                1  0.142450
C:\Windows\System32\conhost.exe                                89 12.678063
C:\Windows\System32\taskhostw.exe                              94 13.390313
C:\Program Files\Microsoft Office\root\Office16\OUTLOOK.EXE    98 13.960114

It found both planted binaries, but rare returns up to limit rows (the default is 10) whether or not they're unusual, so three of these five are normal. On a real fleet with thousands of one-off installers, "rare overall" is noise. Rare across hosts, with the parent process attached, is the more useful question:

index=lab sourcetype="lab:winsec:json" EventCode=4688
| stats count dc(Computer) as hosts values(Computer) as seen_on values(ParentProcessName) as parents by NewProcessName
| where hosts <= 2
| sort count
         NewProcessName          count hosts seen_on                          parents
-------------------------------- ----- ----- ------- ---------------------------------------------------------
C:\Users\Public\rclone.exe           1     1 WS-114  C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe
C:\Windows\System32\certutil.exe     1     1 WS-114  C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe

Two rows, same host, same parent: certutil is a common download tool (T1105) and rclone is a common exfiltration tool (T1567.002). That's a hunt lead, not a verdict. Pull the CommandLine for both and check whether IT installed rclone on purpose.

tstats vs search

tstats is much faster than stats because it reads index-time fields from tsidx files instead of raw events, which is why models love it. The catch, as Step 3 showed, is that it only sees indexed fields (index, sourcetype, host, source, _time, plus anything extracted at index time or in an accelerated data model). On this lab data, this works:

| tstats count where index=lab sourcetype="lab:winsec:json" by _time span=1h
           _time            count
--------------------------- -----
2026-09-22 02:00:00.000 PDT    25
2026-09-22 03:00:00.000 PDT    31
2026-09-22 06:00:00.000 PDT    40
2026-09-22 07:00:00.000 PDT   104
...

Even this cheap volume baseline shows the 2 AM and 3 AM bumps on an otherwise idle overnight source. Use tstats for volume, for "which hosts and sourcetypes are reporting," and against accelerated data models if your environment has them. Use a normal search plus stats when you need search-time fields like IpAddress. When a model hands you tstats, ask which of the fields it filters or groups on are indexed. If you can't answer that, run it next to the stats version and compare the counts.

Diagram of the loop to generate Splunk SPL with an LLM: fieldsummary supplies real field names, the model drafts a search, the search/v2/parser endpoint rejects syntax errors, the lab run catches empty or wrong results against planted answers, and only searches that find the planted activity are saved
Diagram of the loop to generate Splunk SPL with an LLM: fieldsummary supplies real field names, the model drafts a search, the search/v2/parser endpoint rejects syntax errors, the lab run catches empty or wrong results against planted answers, and only searches that find the planted activity are saved Image: RedRouter, Original

Automate the loop: draft, parse, run, compare

The loop is short: the model drafts, Splunk judges, and the exact output goes back. This validator is the one we ran in the lab. It parses with search/v2/parser, then streams results from search/v2/jobs/export. Point it only at a lab or test instance.

# check_spl.py
import json, os, requests, urllib3
urllib3.disable_warnings()  # lab instance on localhost uses Splunk's self-signed cert
BASE = "https://127.0.0.1:8089/services"
AUTH = ("admin", os.environ["SPLUNK_LAB_PASSWORD"])

def check(spl, earliest="0"):
    q = spl if spl.lstrip().startswith("|") else "search " + spl
    p = requests.post(f"{BASE}/search/v2/parser", auth=AUTH, verify=False,
                      data={"q": q, "output_mode": "json"})
    if p.status_code != 200:
        return {"stage": "parse", "messages": p.json().get("messages")}
    r = requests.post(f"{BASE}/search/v2/jobs/export", auth=AUTH, verify=False,
                      data={"search": q, "earliest_time": earliest, "output_mode": "json"})
    rows = [json.loads(l)["result"] for l in r.text.splitlines()
            if l.strip() and "result" in json.loads(l)]
    return {"stage": "run", "rows": len(rows), "sample": rows[:20]}

On the lab it returned {"stage": "parse", "messages": [{"type": "FATAL", "text": "Unknown search command 'filter'."}]} for the filter draft, {"stage": "run", "rows": 0} for the src_ip draft, and one row, 203.0.113.45 with 25 users, for the fixed spray search.

The drafting side calls RedRouter's OpenAI-compatible endpoint. The base URL is https://redrouter.org/v1 and the key goes in a Bearer header, per the RedRouter quickstart. We didn't have an API key on the lab box, so this half is a sketch:

import json, os
from openai import OpenAI
from check_spl import check

client = OpenAI(base_url="https://redrouter.org/v1",
                api_key=os.environ["REDROUTER_API_KEY"])

SYSTEM = ("You write Splunk SPL (not SPL2, not KQL). Use only the fields listed. "
          "Filter after stats with where; aggregate functions such as dc() belong in stats. "
          "Absolute times use %m/%d/%Y:%H:%M:%S. In where, wildcards need like() with %. "
          "Escape backslashes in quoted Windows paths. Use tstats only on indexed fields. "
          "Return one search and nothing else.")

FIELDS = "index=lab sourcetype=lab:winsec:json fields: EventCode, TargetUserName, IpAddress, Computer, ..."
GOAL = "Find source IPs that failed logon (4625) against 10 or more distinct accounts on 09/22/2026."
EXPECT = {"203.0.113.45"}  # planted answer

def draft(feedback=""):
    r = client.chat.completions.create(
        model="glm-5.3-flash-red", temperature=0,
        messages=[{"role": "system", "content": SYSTEM},
                  {"role": "user", "content": f"{FIELDS}\n\nGoal: {GOAL}\n\n{feedback}"}])
    return r.choices[0].message.content.strip().strip("`")

spl = draft()
for _ in range(4):
    result = check(spl)
    found = {row.get("IpAddress") for row in result.get("sample", [])}
    if result["stage"] == "run" and found == EXPECT:
        break
    spl = draft(f"Your search:\n{spl}\n\nSplunk returned:\n{json.dumps(result)[:4000]}\n"
                f"Expected exactly these IPs: {sorted(EXPECT)}. Fix it.")
print(spl)

The stop condition matters more than anything else in that code. "It parsed" and "it returned rows" are both too weak. The loop ends only when the search returns the planted answer and nothing else. If you'd rather keep Claude Code or OpenCode as the planner and hand just the drafting step to another model, our broker pattern guide shows that setup.

If your detections start life as Sigma rules, convert them with pySigma's Splunk backend rather than asking a model to translate; our guide to Sigma and YARA rules with an LLM covers that conversion.

What to send the model

Hunting starts from production data, so be deliberate about prompts.

  • Send the field list from fieldsummary, the index and sourcetype, and the goal in plain words. That's usually enough.
  • Send Splunk's exact error text or row count back, not your interpretation of it.
  • If the model needs sample events, send the shape with placeholder values or documentation ranges (192.0.2.0/24, 198.51.100.0/24, 203.0.113.0/24), as in this lab. Don't paste real usernames, hostnames, internal IPs or command lines with secrets in them.

On RedRouter, Zero Data Retention is an opt-in setting and off by default. The data handling docs explain what's stored when content storage is on, how API-key content storage works, and how to turn ZDR on. Our security page covers how we handle security workloads.

Which model to use

For drafting SPL, we'd start with GLM 5.3 Flash Red (glm-5.3-flash-red). On docs.redrouter.org/models it lists at $0.25 per 1M input tokens, $0.13 per 1M cached input tokens and $1.00 per 1M output tokens, with a 1,048,576-token context window. A draft-and-fix round like the one above is a few thousand tokens. If the hunt is part of a broader authorized red-team or purple-team engagement, red-cyber-1 (Beta) lists at $0.28 / $0.13 / $1.10 per 1M. Plans are on /pricing. Check the models page for current rates before you budget.

Common LLM SPL mistakes

Mistake in the draftWhat Splunk did in the labFix
filter users > 10 after statsUnknown search command 'filter'.where users > 10
where dc(TargetUserName) > 10The 'dc' function is unsupported or undefined.stats dc(TargetUserName) as users, then where users > 10
earliest="2026-09-22T00:00:00"Invalid value ... for time term 'earliest'earliest="09/22/2026:00:00:00"
by src_ip, user on raw Windows fields0 rows, no warningUse the names from fieldsummary
tstats ... where EventCode=4625 by IpAddress0 rows, no warningstats, or tstats on indexed fields only
where TargetUserName="svc-*"0 rowswhere like(TargetUserName, "svc-%")
NewProcessName="C:\Users\Public\*"No matching fields exist.Double the backslashes
stats count by IpAddress, TargetUserName for sprayingFound the brute force, missed the spraydc(TargetUserName) per source
bin _time span=15m with a tight thresholdSpray split 14 and 11 across bucketsLower threshold, wider span, or both views
earliest=-24h on replayed data0 rowsAbsolute times for validation

Validation checklist

  • The draft uses only fields from fieldsummary for this index and sourcetype.
  • search/v2/parser returns HTTP 200.
  • The search has explicit time bounds. Absolute for testing, relative for scheduling.
  • It returns every planted true positive, and you checked the exact values, not just "rows > 0."
  • It stays quiet on at least one planted look-alike (here, the brute force for the spray hunt and vice versa).
  • Any tstats filters and groups only on indexed fields, and its counts match the stats version.
  • Thresholds were checked against bin boundaries.
  • Before scheduling, run it over a normal week and count the results.

FAQ

Can an LLM generate Splunk SPL that works the first time?

Sometimes, but plan on testing it. In this lab, three of the drafts failed to parse, four parsed and returned nothing, and one returned a correct-looking row while missing half of what it was meant to find. Each fix was quick once Splunk showed the output. Treat the model as a fast drafter and your lab instance as the judge.

How do I check an LLM Splunk search without running it?

POST it to the search/v2/parser REST endpoint on a test instance. It returns HTTP 400 with a FATAL message for unknown commands, misplaced functions and bad time terms, and HTTP 200 with the parsed command list when the syntax is valid. It can't tell you whether the fields exist or the logic is right; only running it on known data can.

Why does my AI-written SPL detection query return no results?

Usually one of three things: a field name that doesn't exist in your data (often a CIM name like src_ip), tstats filtering on a field that is only extracted at search time, or a time range that doesn't cover the data. Splunk doesn't warn about any of them. Check fields with fieldsummary and give the search explicit earliest and latest values.

When should I use tstats instead of stats in Splunk?

Use tstats when everything you filter and group on is indexed: index, sourcetype, host, source, _time, index-time extractions, or fields in an accelerated data model. It's much faster there. For search-time fields such as JSON fields extracted with KV_MODE = json, use a normal search with stats.

What time format does Splunk SPL use for earliest and latest?

%m/%d/%Y:%H:%M:%S, for example earliest="09/22/2026:00:00:00". ISO 8601 strings fail with "Invalid value ... for time term 'earliest'." SPL2 documents a different format, which is one reason models mix them up.

How do I detect password spraying in Splunk?

Count distinct target accounts per source over a time window: stats dc(TargetUserName) as users by IpAddress, then where users >= <threshold>. Counting failures per source and account detects brute force instead. If you add bin, remember that a spray can straddle a bucket boundary.

Is it safe to paste Splunk data into an LLM prompt?

Send field names, the goal and Splunk's error text, not raw events. If the model needs examples, use placeholder values and documentation IP ranges. On RedRouter, Zero Data Retention is opt-in and off by default; see the data handling docs.

Related guides

Sources