0

'Hello, i got my information parsed the way I want it. But now I'm trying to save the output to a possible .txt file. Im not sure what to type in the "backup.write()" if I type the "output" variable it saves the whole output not the parsed section.'

    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()
Tes3awy
  • 2,166
  • 5
  • 29
  • 51
Donny
  • 1
  • 1
  • Can you describe what is your **desired result**, and **current result** of given code? And if possible, breakdown your code into snippets as a step by step walkthrough to address your desired result until we get to the specific question/issue. That way, you may also edit your question's title to a more specific and directly answerable question. You may use Stack Overflow's [How to Ask](https://stackoverflow.com/help/how-to-ask) and [this checklist](https://codeblog.jonskeet.uk/2012/11/24/stack-overflow-question-checklist/) as your guide before publishing your question. – Alex Pappas Sep 02 '21 at 15:21
  • CCerberus, my desired result is to run the Cisco IOS command "show interface status" and parse the data using textfsm module to only provide the interfaces that are in the shtudown. Second step would be to save the parsed data into a .txt file. I got the first part down just need help with the second part. Thank you for taking a look. – Donny Sep 02 '21 at 15:30

1 Answers1

0

my desired result is to run the Cisco IOS command "show interface status" and parse the data using textfsm module to only provide the interfaces that are in the shtudown.

I tried the same on show ip interface brief, because I have no access to a Cisco switch right now. For show interfaces status both methods apply but with different output modifier or if condition.

So to get the following output, you can do it in two ways:

1- CLI Output Modifier

show ip interface brief | include down

And the rest is left for TextFSM to parse the output

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

2- Python

You can get the whole output from show ip interface brief and loop over all parsed interfaces and set an if condition to get the down interfaces only. (Recommended)

# 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"
]

Exporting a List[Dict] to a .txt file makes no sense. You don't have any syntax highlighting or formatting in .txt files. It's better to export it to a JSON file. So a complete example of what you want to achieve can be something like:

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")
Tes3awy
  • 2,166
  • 5
  • 29
  • 51