Search code examples
pythonauthenticationtelnetverificationcisco

Verifying Authentication to a Telnet Session in Python


I am trying to telnet into a Cisco Switch and run a couple of commands on it. I am able to check if the host doesn't exist, not sure how to check if the username or password is correct. This is what I got so far(This is part of my class)

def login(self):
    if self.user_name and self.password: 
        try:
            self.connection=telnetlib.Telnet(self.telnet_host)
            try:
                self.connection.read_until('sername:',1)
                self.connection.write(self.user_name+'\r\n')
                self.connection.read_until('assword:',1)
                self.connection.write(self.password+'\r\n')
                self.connection.read_until(self.prompt,1)
                print "Connected"
                self.loggedON=True
            except EOFError:
                print "Authentication to "+ self.telnet_host+" failed.\n"
                return
        except: 
            print "Can't connect to "+self.telnet_host+"\n"
            return
    else:
        if not self.user_name:
            self.user_name=raw_input("Username: ")
            self.login()
        else:
            self.password=raw_input("Password: ")
            self.login()

It will still say it is connected even if the wrong password or username.


Solution

  • You could also try Exscript:

    from Exscript.util.start import quickstart
    
    def do_something(conn):
        conn.autoinit()
        conn.execute('show version')
    
    quickstart('telnet://localhost', do_something)
    

    The quickstart() function asks the user for username and password (use start() if that is not what you want). Login failure (and other errors) are handeled automatically. You may also want to look at Exscript.util.start.