Splunk® Enterprise

Developing Views and Apps for Splunk Web

Splunk Enterprise version 8.1 will no longer be supported as of April 19, 2023. See the Splunk Software Support Policy for details. For information about upgrading to a supported version, see How to upgrade Splunk Enterprise.

Example script that polls a database

Here is an example of a scripted input that polls a database. In the configuration for the script, you specify the interval at which the script runs.

Note: No script can be a "one size fits all." The purpose of this example is to provide a basic framework that you modify and customize for your specific purposes. This script polls a database and writes the records retrieved to stdout. The data queries, connection, authentication, and processing of the query have been simplified.

This example script does the following:

  • Builds a query to extract 1000 records from a database
  • Connects to a database
  • Stores the key to the database as an eventID.
  • Writes the last eventID retrieved from the database to file to track which events have been indexed.
  • Executes the query and writes the results to stdout for the Splunk platform to index.

Pseudo-code for the example script

# Script to poll a database
#
# Reads 1000 records from a database, 
# writes them to stdout for indexing by splunk,
# tracks last event read
#
# SQL Query information:
#
# Microsoft SQL Server syntax
# SELECT TOP 1000 eventID, transactionID, transactionStatus FROM table 
#    WHERE eventID > lastEventID ORDER BY eventID
#
# 
# MySQL syntax
# SELECT eventID, transactionID, transactionStatus FROM table 
#     WHERE eventID > lastEventID LIMIT 1000 ORDER BY eventID
#
#
# Oracle syntax
# SELECT eventID, transactionID, transactionStatus FROM table 
#    WHERE eventID > lastEventID AND ROWNUM <= 1000 ORDER BY eventID
# 
# ==========================
# Database Fields
# ==========================
# 
# eventID                        autoincrement unsigned
# transactionId char             8
# transactionStatus varchar     32
#
# =========================
# Sample Data
# =========================
#
# 1 A1756202    submitted
# 2 C1756213    acknowledged
# 3 A1756202    rejected
# 4 N1756754    submitted
# 5 C1756213    completed


import needed files

define SQL query

define SQL connection information
  db server address
  db user
  db pw
  db name

define path to file that holds eventID of last record read
  last_eventid_filepath

read eventID from last_eventid file

connect to database

execute SQL query

write query results to stdout

close db connection

update eventID in last_eventid file

Script example, poll a database (Python)

Here is a python version of the database poll example. The code has been simplified for readability and does not necessarily represent best coding practices. Please modify according to your needs.

The Python version of the example accesses a Microsoft SQL Server database. It assumes you have all the necessary libraries referenced in the script.

This example requires the following:

  • pymssql language extension
  • FreeTDS 0.63 or newer (*nix and Mac OS X platforms only)

This script has been made cross-compatible with Python 2 and Python 3 using python-future.

hello_db_poll_script.py

#!/usr/bin/python

from __future__ import print_function
from builtins import str
import _mssql
import os
import sys
from time import localtime,strftime
import time

sql_server = "SQLserver" #Address to database server
database = "hello_db_database"
sql_uname = "splunk_user"
sql_pw = "changeme"
columns = 'TOP 1000 eventID, transactionID, transactionStatus'
table = 'hello_table'

countkey = 'eventID'

last_eventid_filepath = "" # user supplies correct path

# Open file containing the last event ID and get the last record read
last_eventid = 0;
if os.path.isfile(last_eventid_filepath):
    try:
        last_eventid_file = open(last_eventid_filepath,'r')
        last_eventid = int(last_eventid_file.readline())
        last_eventid_file.close()

    # Catch the exception. Real exception handler would be more robust    
    except IOError:
        sys.stderr.write('Error: failed to read last_eventid file, ' + last_eventid_filepath + '\n')
        sys.exit(2)
else:
    sys.stderr.write('Error: ' + last_eventid_filepath + ' file not found! Starting from zero. \n')

# Fetch 1000 rows starting from the last event read
# SELECT TOP 1000 eventID, transactionID, transactionStatus FROM table WHERE eventID > lastEventID ORDER BY eventID
sql_query = 'SELECT ' + columns + ' FROM ' + table + ' WHERE ' + countkey + ' > ' + str(last_eventid) + ' ORDER BY ' + countkey

try:
    conn = _mssql.connect(sql_server, sql_uname, sql_pw, database)
    conn.execute_query(sql_query)
    # timestamp the returned data
    indexTime = "[" + strftime("%m/%d/%Y %H:%M:%S %p %Z",localtime()) + "]"
    for row in conn:
    	print("%s eventID=%s, transactionID=%s, transactionStatus=%s" % (indexTime, row['eventID'], row['transactionID'], row['transactionStatus']))

    this_last_eventid = row['eventID'] 

# Catch the exception. Real exception handler would be more robust    
except _mssql.MssqlDatabaseException as e: 
    sys.stderr.write('Database Connection Error!\n')
    sys.exit(2)
    
finally:
    conn.close()
    
if this_last_eventid > 0:
   try:
     last_eventid_file = open(last_eventid_filepath,'w')
     last_eventid_file.write(this_last_eventid)
     last_eventid_file.close()
   # Catch the exception. Real exception handler would be more robust    
   except IOError:
     sys.stderr.write('Error writing last_eventid to file: ' + last_eventid_filepath + '\n')
     sys.exit(2)
Last modified on 13 August, 2019
Writing reliable scripts   Customization options and caching

This documentation applies to the following versions of Splunk® Enterprise: 7.0.0, 7.0.1, 7.0.2, 7.0.3, 7.0.4, 7.0.5, 7.0.6, 7.0.7, 7.0.8, 7.0.9, 7.0.10, 7.0.11, 7.0.13, 7.1.0, 7.1.1, 7.1.2, 7.1.3, 7.1.4, 7.1.5, 7.1.6, 7.1.7, 7.1.8, 7.1.9, 7.1.10, 7.2.0, 7.2.1, 7.2.2, 7.2.3, 7.2.4, 7.2.5, 7.2.6, 7.2.7, 7.2.8, 7.2.9, 7.2.10, 7.3.0, 7.3.1, 7.3.2, 7.3.3, 7.3.4, 7.3.5, 7.3.6, 7.3.7, 7.3.8, 7.3.9, 8.0.0, 8.0.1, 8.0.2, 8.0.3, 8.0.4, 8.0.5, 8.0.6, 8.0.7, 8.0.8, 8.0.9, 8.0.10, 8.1.0, 8.1.1, 8.1.2, 8.1.3, 8.1.4, 8.1.5, 8.1.6, 8.1.7, 8.1.8, 8.1.9, 8.1.11, 8.2.0, 8.2.1, 8.2.2, 8.2.3, 8.2.4, 8.2.5, 8.2.6, 8.2.7, 8.2.8, 8.2.9, 8.2.10, 8.2.11, 8.2.12, 9.0.0, 9.0.1, 9.0.2, 9.0.3, 9.0.4, 9.0.5, 9.0.6, 9.0.7, 9.0.8, 9.0.9, 9.0.10, 9.1.0, 9.1.1, 9.1.2, 9.1.3, 9.1.4, 9.1.5, 9.1.6, 9.1.7, 9.2.0, 9.2.1, 9.2.2, 9.2.3, 9.2.4, 9.3.0, 9.3.1, 9.3.2, 8.1.10, 8.1.12, 8.1.13, 8.1.14


Was this topic useful?







You must be logged into splunk.com in order to post comments. Log in now.

Please try to keep this discussion focused on the content covered in this documentation topic. If you have a more general question about Splunk functionality or are experiencing a difficulty with Splunk, consider posting a question to Splunkbase Answers.

0 out of 1000 Characters