Netmiko / textfsm



'你好,我得到了我想要的方式的信息解析。但现在我要保存输出到一个可能的。txt文件。我不知道该在"backup.write()"如果我输入"output"变量,它保存整个输出,而不是已解析的部分。

connection = ConnectHandler(**cisco_device)
# print('Entering the enable mode...')
# connection.enable()
prompt = connection.find_prompt()
hostname = prompt[0:-1]
print(hostname)

output = connection.send_command('show interfaces status', use_textfsm=True)

for interface in output:
if interface['status'] == 'notconnect':
print(f"interface {interface['port']} n shutdown")

print(hostname)
print('*' * 85)

# minute = now.minute
now = datetime.now()
year = now.year
month = now.month
day = now.day
hour = now.hour

# creating the backup filename (hostname_date_backup.txt)
filename = f'{hostname}_{month}-{day}-{year}_backup.txt'

# writing the backup to the file
with open(filename, 'w') as backup:
backup.write()
print(f'Backup of {hostname} completed successfully')
print('#' * 30)

print('Closing connection')
connection.disconnect()

我想要的结果是运行Cisco IOS命令"show interface status"使用textfsm模块解析数据,只提供shutdown中的接口。

我在show ip interface brief上尝试了同样的操作,因为我现在没有访问Cisco交换机的权限。对于show interfaces status,这两种方法都适用,但输出修饰符不同或if条件不同。

因此,要获得以下输出,可以通过以下两种方式:1- CLI Output Modifier

show ip interface brief | include down

剩下的留给TextFSM解析输出

[{'intf': 'GigabitEthernet2',
'ipaddr': 'unassigned',
'proto': 'down',
'status': 'administratively down'},
{'intf': 'GigabitEthernet3',
'ipaddr': '100.1.1.1',
'proto': 'down',
'status': 'down'}]

2 - Python

您可以从show ip interface brief获得整个输出,并循环所有已解析的接口,并设置if条件以仅获取down接口。(推荐)

# Condition for `show ip interface brief`
down = [
intf
for intf in intfs
if intf["proto"] == "down" or intf["status"] in ("down", "administratively down")
]
# Condition for `show interfaces status`
down = [
intf
for intf in intfs
if intf["status"] == "notconnect"
]

导出List[Dict].txt文件没有意义。在.txt文件中没有任何语法高亮显示或格式化。最好将其导出为JSON文件。所以你想要达到的一个完整的例子可以像这样:

import json
from datetime import date
from netmiko import ConnectHandler
device = {
"device_type": "cisco_ios",
"ip": "x.x.x.x",
"username": "xxxx",
"password": "xxxx",
"secret": "xxxx",
}
with ConnectHandler(**device) as conn:
print(f'Connected to {device["ip"]}')
if not conn.check_enable_mode():
conn.enable()
hostname = conn.find_prompt()[:-1]
intfs = conn.send_command(
command_string="show ip interface brief", use_textfsm=True
)
print("Connection Terminated")
down = [
intf
for intf in intfs
if intf["proto"] == "down" or intf["status"] in ("down", "administratively down")
]
with open(file=f"{hostname}_down-intfs_{date.today()}.json", mode="w") as f:
json.dump(obj=down, fp=f, indent=4)
print(f"Completed backup of {hostname} successfully")
# In case you have to export to text file
# with open(file=f"{hostname}_down-intfs_{date.today()}.txt", mode="w") as f:
#     f.write(down)
# print(f"Completed backup of {hostname} successfully")

相关内容

  • 没有找到相关文章

最新更新