Splunk Search

How do I write the regex to identify the sourceip that can be found in different locations in my logs?

splunkn
Communicator

I have logs like below

1.1.1.1 This is my sourceip
2.2.2.2 My source ip is 1.1.1.2

I have a situation where in some events, my sourceip comes first in the line (AS in First EVENT), and other events, IPs come first, but this is not sourceip. Whatever comes after (in this case, 1.1.1.2) is my source ip. How to write a regex for this lookahead?

Thanks

Tags (2)
0 Karma
1 Solution

javiergn
Super Champion

Try this:

| rex field=_raw max_match=0 "(?<ip>\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})"
| eval sourceIP = mvindex(ip, mvcount(ip)-1)

This is basically going to do the following:
- Store all the IPs in your event in the ip multivalued field (even if there's only one match, it will be a multivalued field with one value only)
- Retrieve the latest ip from the multivalued field and assign to sourceIP

Example:

| stats count | fields - count
| eval raw = "1.1.1.1 This is my sourceip; 2.2.2.2 My source ip is 1.1.1.2"
| eval raw = split(raw, ";")
| mvexpand raw
| rex field=raw max_match=0 "(?<ip>\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})"
| eval sourceIP = mvindex(ip, mvcount(ip)-1)

Output: see attached picture
alt text

View solution in original post

0 Karma

javiergn
Super Champion

Try this:

| rex field=_raw max_match=0 "(?<ip>\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})"
| eval sourceIP = mvindex(ip, mvcount(ip)-1)

This is basically going to do the following:
- Store all the IPs in your event in the ip multivalued field (even if there's only one match, it will be a multivalued field with one value only)
- Retrieve the latest ip from the multivalued field and assign to sourceIP

Example:

| stats count | fields - count
| eval raw = "1.1.1.1 This is my sourceip; 2.2.2.2 My source ip is 1.1.1.2"
| eval raw = split(raw, ";")
| mvexpand raw
| rex field=raw max_match=0 "(?<ip>\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})"
| eval sourceIP = mvindex(ip, mvcount(ip)-1)

Output: see attached picture
alt text

0 Karma

tgdvopab
Path Finder

You can use two different regex:
for the first event: rex field=yourfield "^(?P(\d.){4})This is my sourceip"
for the 2nd even: rex field=youfield ".*My source ip is\s(?P(\d.){3}\d)"

0 Karma
Get Updates on the Splunk Community!

Splunk Observability as Code: From Zero to Dashboard

For the details on what Self-Service Observability and Observability as Code is, we have some awesome content ...

[Puzzles] Solve, Learn, Repeat: Character substitutions with Regular Expressions

This challenge was first posted on Slack #puzzles channelFor BORE at .conf23, we had a puzzle question which ...

Shape the Future of Splunk: Join the Product Research Lab!

Join the Splunk Product Research Lab and connect with us in the Slack channel #product-research-lab to get ...