# coding: utf8 import re, sys import pexpect # enable/disable debug mode DEBUG = False def telnet_login(ip, pwd, cmd, ps): child = pexpect.spawn('telnet %s' % ip) # 是否启用调试模式, 默认位False,在上面设置DEBUG=True后开启调试模式 if DEBUG: print '[' + '-' * 30 + "DEBUG INFO START" + '-' * 30 + "]\n" child.logfile_read = sys.stdout # telnet输出至标准输出 child.expect('(?i)Password: ', timeout=2) # 匹配Password: ,注意问号后有空格 child.send(pwd + '\r') # 这里要输入密码+回车(\r),不要用sendline方法 child.expect('Please press ENTER.\r\n', timeout=1) child.send('\r') # 根据上面提示,按回车后继续 child.expect(ps[0], timeout=2) # 匹配第1提示符 child.send('system-view' + '\r') # 进入system-view视图 child.expect(ps[1], timeout=2) # 匹配第2个提示符 output = "" out="" for tcmd in cmd: child.send(tcmd + '\r') # 执行命令 child.expect(tcmd + '\r') # 匹配命令回显 child.expect(ps[1], timeout=2) # 匹配命令执行完提示符 out = child.before # 捕获命令的输出结果 if out != '': out = re.sub('.*\[.*', '', out) # 处理输出结果的尾部提示符 out = re.sub('\015', '', out) # 处理输出结果的尾部^M(实际上是回车符) output += "\n" + tcmd + "执行结果: \n"+"\n".join([j.strip() for j in out.split('\n') if j != '']) # 删除命令输出中的多余空行和行首尾空格 return child, output if __name__ == '__main__': host = "192.168.*.*" password = "######" command = ['dis ip', 'dis arp'] # 执行命令列表 prompt = ['\)\>', '\)\]'] # 提示符 c, cmdstdout = telnet_login(host, password, command, prompt) # debug开启后, 也可以把命令输出结果写入文件 if DEBUG: with open("/tmp/telnet_output.txt", "w") as f: f.write(cmdstdout) print '\n\n[' + '-' * 30 + "DEBUG INFO END" + '-' * 30 + "]\n" print '[' + '-' * 30 + "telnet command output" + '-' * 23 + "]\n" print cmdstdout # 打印命令执行结果 c.close(force=True)
## 注释: 其中 c 和 cmdstdout 是用来接收 telnet_login 函数返回 的 child 和 output