Search code examples
pythonciscopexpect

pexpect setecho not working


I am trying to telnet to Cisco Router and give commands using pexpect. Its working, but the sendline() repeats in the output. even after using setecho to False. Code is:

'''
Created on Nov 19, 2012

@author: Amit Barik
'''

import pexpect

hostname = 'hostname'
login_cmd = 'telnet ' + hostname + '.net'
username = 'username'
password = 'pwd'
prompt = hostname + '#'

p = pexpect.spawn(login_cmd)
p.setecho(False)
p.logfile = open('Log.log', 'w+')

p.expect('Username:')
print '1',repr(p.before)

p.sendline(username)
p.expect('Password:')
print '2',repr(p.before)

p.sendline(password)
p.expect(prompt)
print '3',repr(p.before)

cmd = 'show clock'
p.sendline(cmd)
p.expect(prompt)
print 'Output for {0}'.format(cmd), repr(p.before)

Output is:

# On Python Console
Output for show clock 'show clock\r\n00:16:40.692 UTC Tue Nov 20 2012\r\n'

# On Log File
Username: username
username
Password: pwd

My Cisco Banner

hostname#show clock
show clock
00:16:40.692 UTC Tue Nov 20 2012
hostname#

Solution

  • So, what I have found is...

    • setecho just doesn't seem to work (in the pexpect.before output, the pexpect.sendline text is present). Only solution is to do string stripping. Something like pseudo code pexpect.before.strip(pexpect.sendline)
    • Also, while logging, logfile_read doesn't contain the echoes, but logfile contains (irrespective of setecho value)