python配置多台交换机_python跟H3C 5024E交换机交互获取交换机的配置信息

该博客展示了如何利用Python的pexpect库通过telnet登录到H3C 5024E交换机,并执行特定命令获取配置信息。通过设置debug模式、匹配密码和提示符、发送命令并处理输出结果,实现自动化交互。
摘要由CSDN通过智能技术生成

# 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

d3d1beddc57447138406a8908f8dd3be.png

原文:http://lancger.blog.51cto.com/8177008/1709901

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值