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!

Announcing Scheduled Export GA for Dashboard Studio

We're excited to announce the general availability of Scheduled Export for Dashboard Studio. Starting in ...

Extending Observability Content to Splunk Cloud

Watch Now!   In this Extending Observability Content to Splunk Cloud Tech Talk, you'll see how to leverage ...

More Control Over Your Monitoring Costs with Archived Metrics GA in US-AWS!

What if there was a way you could keep all the metrics data you need while saving on storage costs?This is now ...