lundi 20 juin 2016

Python script to catch failed commands or warnings messages

I have a little script that telnets into a network switch and executes commands. It works fine but I need it stop and show an error message if any of the commands fail or network give a waning or something.

Here is the code:

import sys
import telnetlib


HOST = "10.10.10.1"
user = "Test"
password = "TestPW"

tn = telnetlib.Telnet(HOST)

tn.read_until("username: ")
tn.write(user + "n")
tn.read_until("password: ")
tn.write(password + "n")

n, match, previous_text = tn.expect([r'Login incorrect', r'$'], 1)
if n == 0:
    print "Invalid Credentials"
    tn.close()
else:
    tn.write("Term len 0n")
    #Reads data from commands.txt file and executes it line by line
    with open("commands.txt") as commands:
        singlecommand = commands.read()
        tn.write(singlecommand)
        print singlecommand
    #Need exception/error checking to catch fail commands or warnings.
    tn.write("exitn")
    tn.write("yn")
    print tn.read_all()
    tn.close()

I want the script to stop executing more commands after a fail command or a warning from CLI that something maybe wrong. It already has the print function so it should display the error message and command that failed.

Here is a example of a failed command:

% Invalid input detected at '^' marker.

Here is an example warning message:

%Warning:

Aucun commentaire:

Enregistrer un commentaire