newwb Q:telnetlib

Bjorn Pettersen bjorn at roguewave.com
Thu Jul 20 16:43:08 EDT 2000


jtoy wrote:
> 
> Hi, Im trying to write a Python script that runs some simple telnet
> commands.  I want to login, enter usrname/password, then enter a few
> command like: cd, pwd, mail, etc.  I followed the example in
> telnetlib.py, but I cant get it to work.  Can someone write a small
> example with the variables I wrote above?  Thanks for your time.
> Jason Toy
> toyboy at toy.eyep.net
> http://toy.eyep.net

Here's a little rsh'ish class that I just created for a similar
purpose...

You would use it like:

  import rsh
  r = rsh.Rsh('remotehost.foo.com', 'user', 'password')
  r('ls')
  r('cd foobar')
  r('pwd')
  r.close()

It's probably not terribly robust (I only needed it to login to one
machine ;-)  It does print out debug information if you pass something
greater than 0 as fourth argument to the constructor. It also at least
makes the following assumptions (change __init__ if they don't match
your situation):

 - remote machine will respond with "login:" when waiting for username
 - "Password:" when waiting for password
 - initial prompt contain '>' or '$'
 - the prompt can be changed by "export PS1=..."

If you make any improvements, I'd love to see them <wink>

hth,
-- bjorn

#rsh.py
import telnetlib

class Rsh:
	def __init__(self, host, user, passwd, debug=0):
		self.prompt = '<bjorn>'
		self.promptre = [self.prompt]
		self.tn = telnetlib.Telnet()
		
		self.debug = debug
		if self.debug:
			self.tn.set_debuglevel(debug)
			
		self.tn.open(host)
		self.tn.expect(['login:'])
		self.tn.write(user + '\n')
		self.tn.expect(['Password:'])
		self.tn.write(passwd + '\n')
		# note expecting initial prompt to have '>' or '$'
		self.tn.expect(['>', '[$]'])
		if self.debug: print 'writing:', 'export PS1="%s "\n' % self.prompt
		self.tn.write('export PS1="%s "\n' % self.prompt)
		#this takes care of the <prompt> in setting it...
		self.tn.expect(self.promptre)
		#and the first prompt
		self.tn.expect(self.promptre)
		
	def __call__(self, cmnd):
		if self.debug: print 'writing:', cmnd 
		self.tn.write(cmnd + '\n')
		if self.debug: print 'expecting:', self.promptre
		return self.tn.expect(self.promptre)[2][:-len(self.prompt)]
		
	def execute(self, cmnd):
		if self.debug: print 'writing:', cmnd 
		self.tn.write(cmnd + '\n')
		if self.debug: print 'expecting:', self.promptre
		return self.tn.expect(self.promptre)
		
	def close(self):
		if self.debug: print 'closing'
		self.tn.close()




More information about the Python-list mailing list