0

“你好,我的信息按照我想要的方式进行了解析。但现在我正在尝试将输出保存到一个可能的 .txt 文件中。如果我输入“输出”变量,我不确定在“backup.write()”中输入什么,它会保存整个输出而不是解析的部分。

    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()
4

1 回答 1

0

我想要的结果是运行 Cisco IOS 命令“显示接口状态”并使用 textfsm 模块解析数据以仅提供 shtudown 中的接口。

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

因此,要获得以下输出,您可以通过两种方式进行:

1- CLI 输出修改器

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-蟒蛇

您可以从所有解析的接口获取整个输出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"
]

将 a导出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")
于 2021-09-04T14:26:08.007 回答