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!

Index This | I am a number, but when you add ‘G’ to me, I go away. What number am I?

March 2024 Edition Hayyy Splunk Education Enthusiasts and the Eternally Curious!  We’re back with another ...

What’s New in Splunk App for PCI Compliance 5.3.1?

The Splunk App for PCI Compliance allows customers to extend the power of their existing Splunk solution with ...

Extending Observability Content to Splunk Cloud

Register to join us !   In this Extending Observability Content to Splunk Cloud Tech Talk, you'll see how to ...