我正在尝试远程登录到 Cisco 路由器并使用 pexpect 发出命令。它的工作,但 sendline() 在输出中重复。即使在使用 setecho 为 False 之后。代码是:
'''
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)
输出是:
# 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#