Skip to main content
 首页 » 编程设计

python之如何将事件参数传递给运行以响应 Splunk 警报的 Python 脚本

2025年05月04日21shihaiming

这是我的脚本,但它不工作,因为它说 sys.arg[8] 超出索引范围。

斯普伦克: 您的警报可以触发 shell 脚本或批处理文件,它们必须位于 $SPLUNK_HOME/bin/scripts 中。使用以下属性/值对:

action.script =

Splunk 目前允许您将参数作为命令行参数和环境变量传递给脚本。这是因为命令行参数并不总是适用于某些界面,例如 Windows。

环境中可用的值如下:

SPLUNK_ARG_0 脚本名称 SPLUNK_ARG_1 返回的事件数 SPLUNK_ARG_2 搜索词 SPLUNK_ARG_3 完全限定的查询字符串 SPLUNK_ARG_4 已保存搜索的名称 SPLUNK_ARG_5 触发原因(例如,“事件数大于 1”) SPLUNK_ARG_6 用于查看已保存搜索的浏览器 URL SPLUNK_ARG_8 存储此搜索结果的文件(包含原始结果) 由于历史原因未使用 SPLUNK_ARG_7。

这些可以在 UNIX shell 中作为 $SPLUNK_ARG_0 等引用,或者在 Microsoft 批处理文件中通过 %SPLUNK_ARG_0% 等引用。在其他语言(perl、python 等)中,使用语言 native 方法访问环境。

#! /usr/bin/python 
 
#Install requests package for python 
import requests 
import csv, gzip, sys 
 
 
# Set the request parameters 
url = 'https://xxxxxxxxdev.service-now.com/api/now/table/new_call' 
user = 'xxxxx' 
pwd = 'xxxxxx' 
 
event_count = int(sys.argv[1])  # number of events returned. 
results_file = sys.argv[8]      # file with search results 
 
# Set proper headers 
headers = {"Content-Type":"application/json","Accept":"application/json"} 
 
for row in csv.DictReader(openany(results_file)): 
output="{" 
for name,val in row.iteritems(): 
   if output!="{": 
           output+="," 
    output += '"'+name+'":"'+val+'"' 
output+="}" 
 
# Do the HTTP request 
response = requests.post(url, auth=(user, pwd), headers=headers,     data='{"short_description":"Theo\'s Test for Splunk to SN","company":"company\'s      domain","u_source":"Service Desk","contact_type":"Alert","description":"Please     place detailed alert detail including recommended steps"}') 
 
# Check for HTTP codes other than 200 
if response.status_code != 201: 
print('Status:', response.status_code, 'Headers:', response.headers, 'Error       Response:',response.json()) 
exit() 
 
# Decode the JSON response into a dictionary and use the data 
#resp=response.json() 
 #print('Status:',response.status_code,'Headers:',response.headers,'Response:',re    sponse.json()) 
print response.headers['location'] 
} 

请您参考如下方法:

我看到您正在使用 openany 命令,但尚未在您的代码中定义它。这会导致问题吗?

否则,这绝对应该有效,它匹配 my sample code和 Splunk docs 中的代码

import gzip 
import csv 
 
def openany(p): 
    if p.endswith(".gz"): 
        return gzip.open(p) 
    else: 
        return open(p) 
 
results = sys.argv[8] 
for row in csv.DictReader(openany(results)): 
    # do something with row["field"]