我的第一个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





posted on 2017-04-06 15:49  winter.shen  阅读(9967)  评论(0编辑  收藏  举报