开发者

Verifying Authentication to a Telnet Session in Python

开发者 https://www.devze.com 2023-03-09 16:48 出处:网络
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

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开发者_StackOverflow中文版 say it is connected even if the wrong password or username.


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.


First of all, you shouldn't have a blanket try/except block like that. Catch exceptions more narrowly. Also, as others have commented, you might consider SNMP.

Having said that, if you push ahead with Telnet, you might as well just reuse someone else's code. I found this for example with a simple Google search.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号