Splunk Search

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

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

class mycommandCommand(StreamingCommand):
    """ %(synopsis)

    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']
               with open(csv_file, 'a') as csvfile:
                   writer = csv.DictWriter(csvfile, fieldnames=csv_columns, delimiter=";")
                   for data in mycv.items():
           except IOError:
               print("I/O error")

           yield event

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

this is the commands.conf:

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

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!

Introducing Splunk Enterprise 9.2

WATCH HERE! Watch this Tech Talk to learn about the latest features and enhancements shipped in the new Splunk ...

Adoption of RUM and APM at Splunk

    Unleash the power of Splunk Observability   Watch Now In this can't miss Tech Talk! The Splunk Growth ...

Routing logs with Splunk OTel Collector for Kubernetes

The Splunk Distribution of the OpenTelemetry (OTel) Collector is a product that provides a way to ingest ...