splunk pyhton数据接口

本文实现利用python splunklib包获取splunk数据

参考官方教程: http://dev.splunk.com/view/python-sdk/SP-CAAAEE5

1.通过接口,执行查询语句,并将获取到的查询结果保存在csv中

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

#定义连接信息
HOST="127.0.0.1"#splunk服务器地址
PORT=8089#端口
USERNAME="admin"#登录名
PASSWORD="passwd"#密码


#设置查询语句
search_query='|tstats count from datamodel=xxxx by domain |sort 10 -count'

#定义查询起始日期和结束日期
start_time="2018-05-01"
end_time="20018-05-31"

def main():
    #连接splunk
    service = client.connect(host=HOST,
                             port=PORT,
                             username=USERNAME, 
                             password=PASSWORD,
                             app='search')
    assert isinstance(service, client.Service)

    #查询参数
    search_kwargs={
                   'earliest_time':start_time+'T00:00:00.000+08:00',
                   'latest_time':end_time+'T00:00:00.000+08:00'
                   }

    jobs=service.jobs
    #执行查询语句
    print("正在查询...")
    job=jobs.oneshot(search_query,**search_kwargs)
    #将结果写入本地domain.csv中
    with open('domain.csv','w+',encoding='utf-8') as fh:
        fh.write("domain,count\n")
        for result in results.ResultsReader(job):
            fh.write(result['domain']+","+result['count']+"\n")
    print("数据已保存到本地...")

main()

2.在splunk中配置任务计划,通过接口获取任务计划执行后的结果

import time,re
import splunklib.client as client
import splunklib.results as results

#配置splunk连接信息
HOST = "localhost"
PORT =8089
USERNAME = "admin"
PASSWORD = "passwd"

#定义splunk中计划任务执行的时间间隔(分钟)
cron_gap_min=5

#通过SDK连接到splunk上
service = client.connect(
    host=HOST,
    port=PORT,
    username=USERNAME,
    password=PASSWORD,
    app="search")

#定义需要查找的任务名
match_string="test"

#获取splunk中所有的任务
jobs = service.jobs
#当前程序执行的时间
now_time=int(round(time.time()))

#将数据导出为csv文本
def get_csv_data():
    for job in jobs:
        #使用正则寻找所有此定时任务产生的任务(活动-任务中能看到的任务)
        if re.search(match_string,job.sid):
            #splunk中任务执行的时间
            run_time=re.findall("\d{10}",job.sid)[0]
            run_time=int(run_time)
            #通过对时间的比较找到最近一次运行
            if now_time-run_time < cron_gap_min*60:
                #等到任务完成
                while not job.is_done():
                    time.sleep(1)
                rr = results.ResultsReader(job.results())
                with open('result.csv','w+') as fh:
                    for result in rr:
                        key=result.keys()
                        n=len(key)
                        for i in range(n-1):
                            fh.write(result[key[i]]+",")
                        fh.write(result[key[n-1]]+"\n")
    print("任务完成...")

#将数据转化为字典形式
def get_dict_data():
    for job in jobs:
        #使用正则寻找所有此定时任务产生的任务(活动-任务中能看到的任务)
        if re.search(match_string,job.sid):
            #splunk中任务执行的时间
            run_time=re.findall("\d{10}",job.sid)[0]
            run_time=int(run_time)
            #通过对时间的比较找到最近一次运行
            if now_time-run_time < cron_gap_min*60:
                #等到任务完成
                while not job.is_done():
                    time.sleep(1)
                rr = results.ResultsReader(job.results())
                for result in rr:
                    #定义一个字典,将每条数据存入字典中
                    res_data={}
                    for key in result.keys():
                        res_data[key]=result[key]
                    return res_data
    print("任务完成...")

if __name__=='__main__':
    data=get_dict_data()

猜你喜欢

转载自blog.csdn.net/d1240673769/article/details/80424161
今日推荐