在python中通过HTTP将日志条目写入splunk

时间:2017-12-08 14:49:20

标签: python splunk splunk-sdk

我们有一个需要将日志发送到splunk的python程序。我们的splunk管理员创建了一个服务收集器HTTP端点,用于将日志发布到以下内容:

  • 索引
  • 令牌
  • 主机名
  • URI

我们无法在splunk python SDK客户端中找到输入URI的位置。例如:

import splunklib.client as client
import splunklib.results as results_util

HOST="splunkcollector.hostname.com"
URI="services/collector/raw"
TOKEN="ABCDEFG-8A55-4ABB-HIJK-1A7E6637LMNO"
PORT=443

# Create a Service instance and log in
service = client.connect(
    host=HOST,
    port=PORT,
    token=TOKEN)

# Retrieve the index for the data
myindex = service.indexes["cloud_custodian"]

# Submit an event over HTTP
myindex.submit("Dummy test python client log")

如您所见,我从不使用URI变量。上面的代码导致:

Traceback (most recent call last):
  File "splunk_log.py", line 15, in <module>
    myindex = service.indexes["cloud_custodian"]
  File "/usr/local/lib/python2.7/site-packages/splunklib/client.py", line 1230, in __getitem__
    raise KeyError(key)
KeyError: UrlEncoded('cloud_custodian')

2 个答案:

答案 0 :(得分:2)

结束使用requests执行股票POST。我不确定splunk客户端是否打算支持HTTP事件收集器。

import requests

url='https://splunkcollector.hostname.com:443/services/collector/event'
authHeader = {'Authorization': 'Splunk {}'.format('ABCDEFG-8A55-4ABB-HIJK-1A7E6637LMNO')}
jsonDict = {"index":"cloud_custodian", "event": { 'message' : "Dummy test python client log" } }

r = requests.post(url, headers=authHeader, json=jsonDict, verify=False)
print r.text

答案 1 :(得分:0)

您应该查看Splunk中的HTTP事件收集器。它就像启用它,生成令牌和拨打电话一样简单。

如果您想将数据发送到Splunk HEC,它看起来像这样

51: lines_to_be_removed=("allow-hotplug wlan0" "iface wlan0 inet manual" "wpa-conf \/etc\/wpa_supplicant\/wpa_supplicant.conf") 52: remove_lines(){ 53: for i in "${lines_to_be_removed[@]}" 54: do 55: sudo sed -i "/$i/,1 d" /etc/network/interfaces 56: done 57: }

https://docs.splunk.com/Documentation/SplunkCloud/6.6.0/Data/UsetheHTTPEventCollector