-1

My program requires telnet to a list of suspect devices, however all of their hostnames are different, they do however, follow a suit every time which I shall enclose below.

My issue is that the telnetlib requires a read_until argument before it attempts to enter a username, in my instance I don't know what that hostname is.

I tried saving a read_all as a variable and reading that, in the hope of extracting the hostname but the command hangs as expected

Code

import telnetlib
username = 'admin'
password = 'password'

text = []
def telnet2():
    tn = telnetlib.Telnet('10.10.10.199')
    tn.write(username + "\r\n")
    if password:
      tn.read_until('Password: ')
      tn.write(password + '\r\n')
      tn.write('enable \r\n')
      tn.write('show poe status \r\n')
      tn.write('show mac-address-table \r\n')
      tn.write('exit \r\n')
    text.append(tn.read_all())

telnet2()

Possible Hostnames

Switch_100-110

Extra

In this instance the hostname is Switch_109 but I wouldn't know that if I hadn't manually connected to check.

** Error messages **

`File "connect2.py", line 18, in telnet2
    print(tn.read_all())
  File "/usr/lib/python2.7/telnetlib.py", line 385, in read_all
    self.fill_rawq()
  File "/usr/lib/python2.7/telnetlib.py", line 576, in fill_rawq
    buf = self.sock.recv(50)`
martineau
  • 119,623
  • 25
  • 170
  • 301
Danny Watson
  • 165
  • 5
  • 24

1 Answers1

0

I ended up having to include a sleep and increasing the debug buffer size to accommodate for the amount of data the buffer was receiving, this may not work 100% for myself as the mac-address-table will change throughout the day when users connect, however I am merely looking for one single MAC address that is on a separate interface from the end users so it will be OK

import time
import telnetlib
username = 'admin'
password = 'password'

text = []
my_text = ''
def telnet2():
    tn = telnetlib.Telnet('10.10.10.199')
    tn.read_until('switch_')
    tn.write(username + "\r\n")
    if password:
      tn.read_until('Password: ')
      tn.write(password + '\r\n')
      tn.write('enable \r\n')
      tn.write('show poe status \r\n')
      time.sleep(1)
      tn.write('\r\n')
      tn.write('enable \r\n')
      tn.write('show mac-address-table \r\n')
      tn.write('\r\n')
      time.sleep(2) # handy for not overloading the buffer straight away/accommodating for time delay due to latency
      tn.write('exit \r\n')
      tn.write('exit \r\n')
      my_text = tn.set_debuglevel(40000) # by changing the debuglevel it will take in more data
      my_text = tn.read_all()
      print(my_text)

telnet2()
Danny Watson
  • 165
  • 5
  • 24