Splunk Search

How to create custom command in python to write result SPL to CSV file?

raindad85
New Member

Hi splunker,

I would like to create a python custom commands to write results of SPL commands in a CSV file.

this is an example of what i want to have:
1 - in Splunk ( version 8.0.2):

...( some spl commands)
| table fields1, fields2, fields3

2 - I would then take the table results of the SPL commands, and write the results in a CSV file in an append mode:
=> if one line exists in the file, do not do anything, else, write the lew line in the file (that is the main goal*)

this is the python code I wrote:

#!/usr/bin/env python3

import sys, csv
from splunklib.searchcommands import dispatch, StreamingCommand, Configuration, Option, validators


@Configuration()
class mycommandCommand(StreamingCommand):
    """ %(synopsis)
    ##Syntax
    %(syntax)
    ##Description
    %(description)
    """

    def stream(self, events):
       # Put your event transformation code here
       mycv = {}
       for event in events:

           mycv['field1'] = event["field1"]
           mycv['field2'] = event["field2"]
           mycv['field3'] = event["field3"]

           csv_file = "tmp/Names.csv"
           csv_columns = ['field1','field2','field3']
           try:
               with open(csv_file, 'a') as csvfile:
                   writer = csv.DictWriter(csvfile, fieldnames=csv_columns, delimiter=";")
                   writer.writeheader()
                   for data in mycv.items():
                       writer.writerows(data)
           except IOError:
               print("I/O error")

           yield event

dispatch(mycommandCommand, sys.argv, sys.stdin, sys.stdout, __name__)

this is the commands.conf:

[mycommand]
filename=mycommand.py
enableheader = true
outputheader = true
requires_srinfo = true
stderr_dest = message
supports_getinfo = true
supports_rawargs = true
supports_multivalues = true
streaming = true

some help ???

I thank in advance,

Labels (1)
0 Karma

splunkettes
Path Finder

This is pretty close to what I'm trying to do as well. Curious if you got it to work?

0 Karma
Get Updates on the Splunk Community!

Detecting Remote Code Executions With the Splunk Threat Research Team

REGISTER NOWRemote code execution (RCE) vulnerabilities pose a significant risk to organizations. If ...

Observability | Use Synthetic Monitoring for Website Metadata Verification

If you are on Splunk Observability Cloud, you may already have Synthetic Monitoringin your observability ...

More Ways To Control Your Costs With Archived Metrics | Register for Tech Talk

Tuesday, May 14, 2024  |  11AM PT / 2PM ET Register to Attend Join us for this Tech Talk and learn how to ...