‘你好,我按我想要的方式解析了我的信息。但现在我正在尝试将输出保存到可能的.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()发布于 2021-09-04 14:26:08
显示我想要的结果是运行Cisco IOS命令“
interface status”,并使用textfsm模块解析数据,以便仅提供数据中的接口。我在
show ip interface brief上也做了同样的尝试,因为我现在无法访问思科交换机。对于show interfaces status,两种方法都适用,但具有不同的输出修饰符或if条件。
因此,要获得以下输出,您可以使用两种方法:
CLI1-输出修改器
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'}]Python 2-
您可以从show ip interface brief获得整个输出,并在所有解析的接口上循环,并设置if条件以仅获取关闭的接口。(推荐)
# 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")https://stackoverflow.com/questions/69021470
复制相似问题