As it is quite common to telnet into a router and run script to gather statistics or modify configurations. And python now is quite popular script. So today i wrote a script implementing logging in a cisco router and running command lines.
Below is the class, it is still simple as lots of exceptions i haven't taken into consideration. But it works well in most cases, i publish here and if have time i will try update it.
import telnetlib,time
TELNET_SLEEP_TIME = 1
class RouterDevice:
host="localhost" port=23 telnet = telnetlib.Telnet()
#telnet.set_debuglevel(1000) def __init__(self, host, port):
self.host=host
self.port=port
def login(self, username, password):
self.telnet.open(self.host, self.port, 1000)
self.telnet.write("\n\n")
time.sleep(TELNET_SLEEP_TIME)
login_str = self.telnet.read_very_eager()
print login_str,
if login_str.endswith("Username: "):
self.telnet.write(username+"\n")
time.sleep(TELNET_SLEEP_TIME)
login_str = self.telnet.read_very_eager()
print login_str
if login_str.endswith("Password: "):
self.telnet.write(password+"\n")
time.sleep(TELNET_SLEEP_TIME)
login_str = self.telnet.read_very_eager()
print login_str
if login_str.endswith("#"):
return True else:
return False
def command(self, cli):
self.telnet.write(cli)
time.sleep(TELNET_SLEEP_TIME)
return self.telnet.read_very_eager()
def close(self):
print self.command("end\n"),
print self.command("quit\n"),
self.telnet.close()
Below is the demo on how to use the class
router1 = RouterDevice("localhost",30001)
if router1.login("cisco","cisco"):
print router1.command("config terminal\n"),
print router1.command("show running\n"),
router1.close()
I will keep publishing more and more useful knowledge on IP networking and also scripts. If you like please share this blog and follow me:)