host 配置端口_【转发】Python读取交换机配置

本文档展示了如何使用Python的pexpect库通过telnet连接到交换机,读取配置,并根据特定条件生成修改命令。主要涉及文件操作、错误处理以及字符串处理。在处理过程中注意了Python3中bytes到str的转换问题,避免了文件写入时出现的换行符异常。
摘要由CSDN通过智能技术生成
Python读取交换机配置 - winter.shen - 博客园​www.cnblogs.com
6cfc572f2fea97b03adabb164903f413.png

第一个Python编码

import pexpect

try:

    for host in open('HK5700IPs.txt','r').readlines():
        print(host)
        #switchIP = host.strip('n')
        switchIP = host
        telnet = 'telnet ' + switchIP
        switchPassword = "password"
        switchEnable = 'screen-length 0 temporary'
        commandTorun = 'display current-configuration interface'
#Login to the switch
        t = pexpect.spawn(telnet)
        t.expect('Password:')
        # t.sendline('sup')
        # t.expect('word:')
        t.sendline(switchPassword)
        t.expect('>')
        t.sendline(switchEnable)
        t.expect('>')

    #Send the command
        t.sendline(commandTorun)
        t.expect('return')
        data =  t.before.decode('utf-8')   #最重要的一点,不能直接转为str必须用转码的方式

    #Closing the Telnet Connection
        t.sendline('quit')
    #t.expect('>')
    #t.sendline('quit')
        t.expect(pexpect.EOF)

    #Opening the file and writing the data to it
        f = open('Temp.txt','w')
        f.write(data)
        f.close()
        new_configure = open(switchIP.strip('n') + '_config.txt', 'w')
        f2 = open('Temp.txt','r')
#       f.close()

        lines = f2.readlines()
        for line in lines:    #读每一行的配置
            if "#" in line:
                new_configure.write(line)
            elif "interface GigabitEthernet" in line:   #找寻端口配置命令,并生成配置命令
                new_configure.write(line)
            elif "traffic-policy P5M inbound" in line:  #找寻对应的端口下是否有限速的配置命令,并生成配置命令
                new_configure.write(" undo traffic-policy inboundn traffic-policy P5Mnew inboundn ")
            elif "traffic-policy P10M inbound" in line:  #找寻对应的端口下是否有限速的配置命令,并生成配置命令
                new_configure.write(" undo traffic-policy inboundn traffic-policy P10Mnew inboundn ")

        f.close()
        new_configure.close()
        print(host+"finish")

except Exception as e:
    print ("The Script failed to login")
    print (str(e))


第一次写出用于工作的编码。
用途,批量生成修改命令。
几个坑说一下:
1、pexpect 无法在window上运行。虽然官方给出的对应的替代命令,但是对应的命令还是不能在windows上运行。

a40914fd83e4862efca3802428b288f8.png

7722cd81bd4292622105786cca8d90bd.png

2、刷出来的代码在处理的时候,出向bytes的问题。

在python3里面的收到数据会被当为bytes类型。

但是后面的使用write()的时候,要求填写的内容必须是str。

一开始我使用直接转码的方式进行,结果导致文件里面都是换行符。后面的程序也没有办法执行。

data = str(t.before)

e43c3f057662a04402eebf01a1ac1f65.png

python3 bytes转 str导致 文件都是换行符合 rn

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值