Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

telnetlib python example

So I'm trying this really simple example given by the python docs:

import getpass
import sys
import telnetlib

HOST = "<HOST_IP>"
user = raw_input("Enter your remote account: ")
password = getpass.getpass()

tn = telnetlib.Telnet(HOST)

tn.read_until("login: ")
tn.write(user + "\n")
if password:
   tn.read_until("Password: ")
   tn.write(password + "\n")

tn.write("ls\n")
tn.write("exit\n")
print tn.read_all()

My issue is that it hangs at the end of the read_all()... It doesn't print anything out. I've never used this module before so I'm trying to get this really basic example to work before continuing. BTW, I'm using python 2.4 Thank you.

like image 907
de1337ed Avatar asked Jun 08 '12 16:06

de1337ed


3 Answers

Okay, I found a solution. Before I entered ls and exit, I needed to first specify the terminal type. Adding

tn.write("vt100\n") 

before the "ls" fixed the problem for me.

like image 76
de1337ed Avatar answered Sep 21 '22 11:09

de1337ed


If you're using Windows, be sure to add carriage return (\r) before the new line character:

tn.write(user.encode('ascii') + "\r\n".encode('ascii'))
like image 26
Kalouste Avatar answered Sep 20 '22 11:09

Kalouste


I know this is late to post but may help others. I also struggled to get this right but here is my piece of code. My telnet would follow certain flow like it would ask for loginID and then Password and then you have to wait for a particular string to be displayed here,which for my case was "DB>" then you can proceed with the command and all. My output would be saved in "out" varible

import os,re,telnetlib
host = "10.xxx.xxx.xxx"
port = 23

telnet = telnetlib.Telnet()
telnet.open(host, port)
telnet.write('loginID\r\n')
telnet.write('Password\r\n')
out = telnet.read_until("DB>", 5)
telnet.write('show cable modem reg\r\n') #Mycommand
out = telnet.read_until("DB>", 5)
telnet.write('quit\r\n')
telnet.close()

For more variations and help, Check the website nullege

like image 37
Anukruti Avatar answered Sep 21 '22 11:09

Anukruti