Almost everything that can be done via the web interface can also be accomplished via the command line. For an overview, see the output of /opt/splunk/bin/splunk help. For help on a specific command, use /opt/splunk/bin/splunk help [commandname].
The most common action performed on the command line is search. For example, have a look at the following code:
$ /opt/splunk/bin/splunk search 'foo' 2012-08-25T20:17:54 user=user2 GET /foo?q=7148356 uid=MzA4MTc5OA 2012-08-25T20:17:54 user=user2 GET /foo?q=7148356 uid=MzA4MTc5OA 2012-08-25T20:17:54 user=user2 GET /foo?q=7148356 uid=MzA4MTc5OA
The things to note here are as follows:
- By default, searches are performed over All time. Protect yourself by including earliest=-1d or an appropriate time range in your query.
- By default, Splunk will only output 100 lines of results. If you need more, use the -maxout flag.
- Searches require authentication, so the user will be asked to authenticate unless -auth is included as an argument.
Most use cases for the command line involve counting events to output to other systems. Let's try a simple stats call to count instances of the word error over the last hour by the host:
$ /opt/splunk/bin/splunk search 'earliest=-1h error | stats count by host'
This produces the following output:
------------ ----- host2 3114 vlb.local 3063
The things to note in this case are as follows:
- earliest=-1h is included to limit the query to the last hour.
- By default, the output is in a tabular format. This is nicer to read but much harder to parse in another scripting language. Use -output to control the output format.
- By default, Splunk will render a preview of the results as the results are retrieved. This slows down the overall execution. Disable preview with -preview as false. Previews are not calculated when the script is not being called from an interactive Terminal, for instance, when run from cron.
To retrieve the output as CSV, try the following code:
$ /opt/splunk/bin/splunk search 'earliest=-1h error | stats count by host' -output csv -preview false
This gives us the following output:
count,host 3120,host2 3078,"vlb.local"
Note that if there are no results, the output will be empty.