Python讀取交換機配置


我的第一個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 inbound\n traffic-policy P5Mnew inbound\n ")
            elif "traffic-policy P10M inbound" in line:  #找尋對應的端口下是否有限速的配置命令,並生成配置命令
                new_configure.write(" undo traffic-policy inbound\n traffic-policy P10Mnew inbound\n ")

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

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

 




第一次寫出用於工作的編碼。
用途,批量生成修改命令。

幾個坑說一下:
1、pexpect 無法在window上運行。雖然官方給出的對應的替代命令,但是對應的命令還是不能在windows上運行。

 

2、刷出來的代碼在處理的時候,出向bytes的問題。

在python3里面的收到數據會被當為bytes類型。

但是后面的使用write()的時候,要求填寫的內容必須是str。

 一開始我使用直接轉碼的方式進行,結果導致文件里面都是換行符。后面的程序也沒有辦法執行。

data = str(t.before)

 

python3 bytes轉 str導致 文件都是換行符合   \r\n






免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM