【问题标题】:write log entry to splunk via HTTP in python在 python 中通过 HTTP 将日志条目写入 splunk
【发布时间】:2017-12-08 14:49:19
【问题描述】:

我们有一个 python 程序需要将日志发送到 splunk。我们的 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')

【问题讨论】:

  • 当您尝试使用 service.indexes.keys() 列出索引时会得到什么?
  • AttributeError: 'Indexes' object has no attribute 'keys'
  • 啊,喜欢自定义类型...怎么样:print(", ".join([str(x) for x in service.indexes]))
  • splunklib.binding.HTTPError: HTTP 404 Not Found -- {"text":"The requested URL was not found on this server.","code":404}
  • 好的,然后尝试获取应用端点(查看他们的 API 文档):service.get(URI) 看看会发生什么。

标签: python splunk splunk-sdk


【解决方案1】:

最终使用 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

【讨论】:

  • 对我有用,还建议在 jsonDict 中包含 time,以便按顺序接收您的消息。根据您的配置,您可能还需要在标题中添加X-Splunk-Request-Channel(随机 GUID)
  • 我也像这样添加'sourcetype':jsonDict = {"index":"cloud_custodian", "sourcetype": "Thor", "event": {...} }
【解决方案2】:

您应该查看 Splunk 中的 HTTP 事件收集器。它就像启用它、生成令牌并进行调用一样简单。

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

&lt;protocol&gt;://&lt;host&gt;:&lt;port&gt;/&lt;endpoint&gt;

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

【讨论】:

    猜你喜欢
    • 2015-04-15
    • 1970-01-01
    • 2022-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-31
    • 1970-01-01
    • 2018-10-15
    相关资源
    最近更新 更多