Topics

| pdf version

Splunk > The IT Search Company

  • Search and navigate IT data from applications, servers and network devices in real-time.
  • Download Splunk

Localized Splunk documentation

Looking for Splunk documentation in other languages?

Ruby Example

This documentation applies to the following versions of Splunk: 4.0 , 4.0.1 , 4.0.2 , 4.0.3 , 4.0.4 , 4.0.5 , 4.0.6

Ruby Example

The following example shows how to use Ruby to authenticate against the Splunk REST API with a generic user name and password. Then, run a search, delete a specific search job and list out available search jobs. Note that the list is returned in XML and not parsed. To parse the results from endpoints, use an XML parser such as libxml. Also, you'll need to install the hpricot gem to get this to work.

require 'net/https'
require 'rubygems'
require 'hpricot'

class SplunkClient
  HOST = 'localhost'
  PORT = 8089
  USER = 'admin'
  PASSWORD = 'changeme'

  def splunk_ssl_post_request(path, data = nil, headers = nil)
    http = Net::HTTP.new(HOST, PORT)
    http.use_ssl = true
    http.verify_mode = OpenSSL::SSL::VERIFY_NONE
    http.post(path, data, headers).body
  end

  def session_key
    @session_key ||= load_session_key
  end

  def load_session_key
    doc = Hpricot(splunk_ssl_post_request("/services/auth/login", "username=#{USER}&password=#{PASSWORD}"))
    (doc/"//sessionkey").inner_html
  end

  def create_job query
    search = "search index=internetmail #{query}"
    splunk_ssl_post_request("/services/search/jobs",
                            "search=#{CGI::escape(search)}",
                            { 'authorization' => "Splunk #{session_key}" })

  end

  def list_jobs
    xml = splunk_ssl_post_request("/services/search/jobs/", nil, {'authorization' => "Splunk #{session_key}"})
    puts xml
  end

  def search_results(sid)
    doc = Hpricot(
      splunk_ssl_post_request("/services/search/jobs/#{sid}/events",
                                          nil,
                                          {'authorization' => "Splunk #{session_key}"}))
    (doc/"/results/result").collect do | result |
      log_text = (result/"field[@k='_raw']/v").inner_text
      Email.new log_text
    end
  end

  def splunk_ssl_delete_request(path, headers = nil)
    http = Net::HTTP.new(HOST, PORT)
    http.use_ssl = true
    http.verify_mode = OpenSSL::SSL::VERIFY_NONE
    http.delete(path, headers).body
  end
 
  def delete_job(sid)
    splunk_ssl_delete_request("/services/search/jobs/#{sid}",
                            { 'authorization' => "Splunk #{session_key}" })
                            
  end
end

# Here's the actual operating code
client = SplunkClient.new
puts client.list_jobs

Thanks to Patrick Shaughnessy for submitting this example.

Revision: 207 | Contact | Privacy Policy | Terms of Use | Community content licensed under Creative Commons