Составление отдельного запроса из содержимого файла с использованием Python - PullRequest
0 голосов
/ 29 мая 2018

Я пытаюсь составить запрос Splunk, извлекая значения из содержимого текстового файла.Здесь я не хочу использовать любые модули / библиотеки Splunk.

Это мой простой код -

import pandas as pd
from pandas import ExcelWriter
from pandas import ExcelFile
import sys

df = pd.read_excel("I:\\splunk_dashboards\\FID_list.xlsx", sheetname='FID_lastweek')
sys.stdout = open("I:\\splunk_dashboards\\FID.txt", "w")


v = df['FID']
#print(df['FID'])

print(v)

Это простой код, в котором он извлекает определенные значения столбца и сохраняет его в текстовом файле.

Следующий шагсостоит в том, чтобы сформировать дополнительный запрос с результатами, сохраненными в текстовом файле.

Например, ниже приведен результат из текстового файла -

0                            CollectionLimitsValidation
1                               PaymentLimitsValidation
2                              AccountDetailsFacadeBean
3                              AccountDetailsFacadeBean

У меня есть дополнительный запрос, как показано ниже вдругой текстовый файл -

index=hfc_new_98764 host=QA FID=$(Value1_from_text_file) OR FID=$(value2_from _text_file) OR.... it goes on upto the final values

Из приведенного выше шаблона мне нужен дополнительный запрос, как показано ниже -

index=hfc_new_98764 host=QA FID=CollectionLimitsValidation OR FID=PaymentLimitsValidation OR FID=.... it goes on upto the final values

Мне нужна помощь, чтобы перебрать значения из текстового файла и сохранить вфайл шаблона файла.

1 Ответ

0 голосов
/ 31 мая 2018

Я могу выполнить описанный выше сценарий с файловыми операциями, и вот мой полный код -

# -*- coding: utf-8 -*-
"""
Created on Wed May 30 18:24:04 2018

@author: Harish
"""

import pandas as pd
from pandas import ExcelWriter
from pandas import ExcelFile
import sys
import fileinput
#import os


#Getting the values from Excel sheet

df = pd.read_excel("I:\\splunk_dashboards\\FID_list.xlsx", sheetname='FID_lastweek')
sys.stdout = open("I:\\splunk_dashboards\\new.txt", "w")
df.FID.unique()
v = df['FID'].to_string(index=False)
pd.options.display.max_colwidth = 200
#print(df['FID'])
#print('"{}"'.format(v))
print(v)


#os.system("script_to_create_FID.py")

#left alignment script
sys.stdout = open("I:\\splunk_dashboards\\aligned_file.txt", "w")
with open("I:\\splunk_dashboards\\new.txt") as f:
    for line in f:
        s = line.lstrip()
        m = s.strip()
        print('"{}"'.format(m))
        #print(m)

#FID and OR values 
prefix = 'FID='
suffix = '  OR'

with open('I:\\splunk_dashboards\\aligned_file.txt', 'r') as src:
    with open('I:\\splunk_dashboards\\final_FID.txt', 'w') as dest:
       for line in src:
           dest.write('%s%s%s\n' % (prefix, line.rstrip('\n'), suffix))


#Added Splunk index here      
for linenum,line in enumerate( fileinput.FileInput("I:\\splunk_dashboards\\final_FID.txt",inplace=1) ):
    if linenum==0 :
        print 'index=hfc_new_98764 host=QA" NOT(WARN=yes)'
        print line.rstrip()
    else:
        print line.rstrip()

#Add sort function at the end
a = '| stats count As NumberOfCalls, count(eval(ERCD=0)) AS "Success" ,count(eval(ERCD!=0)) AS "Failures" by FID | sort – Failures'
with open("I:\\splunk_dashboards\\final_FID.txt","a") as text:    
    text.writelines(a)

Шаг 1 - Создать новый текстовый файл со списком извлеченных FID из Excel Шаг 2 -Отформатируйте текстовый файл. Шаг 3 - добавьте «FID» и «ИЛИ» в начале и в конце запроса. Шаг 4 - Генерация запроса

...