Search code examples
pythonnetworkingscriptinginstancenetmiko

Python / Netmiko: Look for failures in switch log


I am trying to make my program look at the log from the switch and see if the words "words" appear in it.

The part that pulls the log from the switch works, but the part that checks for bad words doesn't. I was able to make the code work for a txt file, but not for the output.

My code:

    net_connect.enable()
    output = net_connect.send_command('show log')
    print(output)
    filename = ('log_files/SW_'+ip_addresses[count]+'_'+TNOW+'.txt')

    SAVE_FILE = open(filename, 'w+')
    SAVE_FILE.write(output)

    print(filename)
    textring = (output)

    with textring as infile:
        text = infile.read()
    words = ['flapping', 'Unexpected', 'down']
    for word in words:
        if word in text:
            print('success')
            with open('warnings/SW_WARNING.txt', 'w+') as save_file:
                save_file.write(text)
            break

This is the error I get:

    Traceback (most recent call last):
    File "script.py", line 150, in <module>
    with textring as infile:
    AttributeError: __enter__

Does anyone know how to make the code look at the output of the switch, as it has not become a file yet?


Solution

  • # Eliminate as unnecessary/error on your "with" statement
    # textring = (output)
    # with textring as infile:
    #    text = infile.read()
    
    for word in ['flapping', 'Unexpected', 'down']:
        if word in output:
            print('success')
            with open('warnings/SW_WARNING.txt', 'w+') as save_file:
                save_file.write(output)
            break