Advertisement
Guest User

telnetlib using class

a guest
Aug 11th, 2016
105
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.98 KB | None | 0 0
  1. #!/usr/bin/env python
  2. import telnetlib
  3. import time
  4. from getpass import getpass
  5. import socket
  6. import sys
  7.  
  8. pynet_rtr1 = u'184.105.247.70'
  9. COMMAND = ('show ip interface brief',)
  10.  
  11. TELNET_PORT = 23
  12. TELNET_TIMEOUT = 6
  13.  
  14. class TN(telnetlib.Telnet):
  15.  
  16.     def __init__(self, ip_addr, TELNET_PORT=23, TELNET_TIMEOUT=6):
  17.         '''' constructor to initialise variables'''
  18.         self.TELNET_PORT = TELNET_PORT
  19.         self.TELNET_TIMEOUT = TELNET_TIMEOUT
  20.         self.ip_addr = ip_addr
  21.         telnetlib.Telnet(self.ip_addr, self.TELNET_PORT, self.TELNET_TIMEOUT)
  22.  
  23.     def __enter__(self):
  24.         try:
  25.             return telnetlib.Telnet(self.ip_addr, self.TELNET_PORT, self.TELNET_TIMEOUT)
  26.         except socket.timeout:
  27.             sys.exit("Connection timed-out")
  28.  
  29.     def login(self, username, password):
  30.         output = self.expect([r'[uU]sername:', r'[lL]ogin:'], TELNET_TIMEOUT)[2] #some router uses Login:
  31.         self.write(username + '\n')
  32.         if password:
  33.             output += self.read_until('ssword:', TELNET_TIMEOUT)
  34.             self.write(password + '\n')
  35.         output += self.read_very_eager() #read eargely and display login process.
  36.         return output
  37.  
  38.     def send_command(self, cmd):
  39.         '''This function will send a command over telnet session and returns a string.'''
  40.         cmd = cmd.strip()
  41.         self.write(cmd + '\n')
  42.         time.sleep(1)
  43.         return self.read_very_eager()
  44.  
  45.     def __exit__(self, ip_addr, TELNET_PORT=23, TELNET_TIMEOUT=6):
  46.         self.close()
  47.  
  48.     def __del__(self):
  49.         self.close()
  50.  
  51. if __name__ == "__main__":
  52.     print "Telnet is not secure, but we will still going to use it"
  53.     username = raw_input("Enter username : ")
  54.     password = getpass()
  55.  
  56.     with TN(pynet_rtr1) as remote_conn:
  57.         print remote_conn.login(username, password)
  58.         time.sleep(1)
  59.         remote_conn.send_command('term len 0')   # disable paging
  60.         print remote_conn.send_command(COMMAND[0])
  61.         time.sleep(6)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement