Добрый день! Первый раз постер здесь. Вот так:
У меня есть скрипт python, реализующий textfsm & pandas. Цель моего сценария - преобразовать выходные данные с сетевых устройств и добавить их в файл xls. В этом файле xls должен быть отдельный лист с данными для каждого устройства. Я дошел до того, что могу извлекать нужные данные, конвертировать их с помощью textfsm, записывать в несколько листов в один и тот же файл xls, но моя проблема заключается в данных, которые записываются в xls.
Я использовал следующие шаги:
В a для l oop:
1. Log into a host (host(s) gathered from a host text file).
2. Gather output from the network device & save to file.
3. Parse text using textfsm.
4. Write parsed data to an xls file to a worksheet. NOTE: if script is ran for multiple hosts, each host will have it's own worksheet in the xls file.
Проблема, с которой я сталкиваюсь, заключается в том, что если число хостов больше одного, каждый последующий лист который создается, он также включает в себя данные с предыдущего листа. Другими словами:
Цель:
-worksheet1 = host1 data
-worksheet2 = host2 data
-etc
Текущая ситуация:
-worksheet1 = host1 data
-worksheet2 = host1 + host2 data
-worksheet3 = host1 + host2 + host3 data
-etc
Код выглядит следующим образом:
from getpass import getpass
from datetime import datetime
import netmiko
import textfsm
import pandas as pd
def make_connection (ip, username, password):
return netmiko.ConnectHandler(device_type='cisco_ios', ip=ip, username=username, password=password)
def get_hosts(file_name):
for line in open(file_name, 'r').readlines():
hosts.append(line.strip())
def to_doc_a(file_name, variable):
f=open(file_name, 'a')
f.write(variable)
f.write('\n')
f.close()
def to_doc_w(file_name, variable):
f=open(file_name, 'w')
f.write(variable)
f.close()
#This will be a list of the devices we want to SSH to
hosts = []
#Pull info from hosts_to_check.txt which is a list of the hosts we want to connect to
#This function pulls those hosts out of the txt file and puts them into a list
get_hosts("hosts_to_check.txt")
fail_file = "device_fail.txt"
results_file = "CURRENT_results.txt"
final_file = "CURRENT_file.txt"
#Clearing all the old info out of the old files
to_doc_w(fail_file, "")
to_doc_w(results_file, "")
to_doc_w(final_file, "")
#Prompt user for login info
username = raw_input("Username: ")
password = getpass()
#Getting template ready
template = open('cisco_ios_show_interfaces.textfsm')
results_template = textfsm.TextFSM(template)
print "Script start!\n"
start_time = datetime.now()
#Make a for loop to hit all the devices
for host in hosts:
print "Checking " + host + "...\n"
try:
#Connect to a device
net_connect = make_connection(host, username, password)
except:
print "Unable to connect to " + host + "!\n"
to_doc_a(fail_file, host)
continue
print "Running output command for " + host + '.\n'
try:
#Run a command and set that to show_int_output
hostname = net_connect.find_prompt()[:-1]
show_int_output = net_connect.send_command_expect('sh interface')
to_doc_w(results_file, show_int_output)
except:
to_doc_a(fail_file, host)
content2parse = open(results_file)
content = content2parse.read()
parsed_results = results_template.ParseText(content)
outfile_name = open(final_file, "w+")
outfile = outfile_name
print(results_template.header)
for s in results_template.header:
outfile.write("%s;" % s)
outfile.write("\n")
counter = 0
for row in parsed_results:
for s in row:
outfile.write("%s;" % s)
outfile.write("\n")
counter += 1
print("Write %d records" % counter)
outfile.close()
print("read of csv file")
sh_int_Df = pd.read_csv(final_file, sep=';' , engine='python')
print("converting to excel")
try:
with pd.ExcelWriter('available_ports.xlsx', engine='openpyxl', mode='a') as writer:
sh_int_Df.to_excel(writer, sheet_name=hostname)
except:
with pd.ExcelWriter('available_ports.xlsx', engine='openpyxl') as writer:
sh_int_Df.to_excel(writer, sheet_name=hostname)
print("conversion complete")
print "Script end!\n"
end_time = datetime.now()
total_time = end_time - start_time
print "Script run time: " + str(total_time) + "\n"
Спасибо!