前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >python跟H3C 5024E交换机交

python跟H3C 5024E交换机交

作者头像
py3study
发布2020-01-07 16:48:25
4890
发布2020-01-07 16:48:25
举报
文章被收录于专栏:python3python3

# 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

wKiom1Y6xLTxb49kAAMdanQloEw662.jpg
wKiom1Y6xLTxb49kAAMdanQloEw662.jpg
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019-09-11 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档