精华内容
下载资源
问答
  • python 交换机路由器 路由表监测 http://blog.csdn.net/b617437942/article/details/52955030
  • python交换机自动化巡检

    千次阅读 2019-09-24 21:46:11
    主要分为远程到交换机,查看转换机状态如:show process cpu | in CPU utilization查看cpu占用率;将查询后的结果记录并保存下来,如结果;11%;读取查询的数据文件;将文件中的数据如11%提取部分需要计算出来;创建...

    概述

            脚本功能功能是全程模拟了人的手工巡检,并收集数据,处理后发送邮件。主要分为远程到交换机,查看转换机状态如:show process cpu | in CPU utilization查看cpu占用率;将查询后的结果记录并保存下来,如结果;11%;读取查询的数据文件;将文件中的数据如11%提取部分需要计算出来;创建excel表格,将上一步获取到的数据填写到表格中;编写固定格式的邮件内容,并将保存好的excel表格附到邮件中发送;编写crontab定时任务,实现全程自动化。

    流程图

    代码

    '''
    Author:myfu
    Date:2019-08-26
    E-mail:myfu@****.com
    
    '''
    
    import pexpect
    import sys
    import time
    import os
    import xlwt
    def cisco_check():
            ip=["10.3.240.14","10.3.240.15","10.3.240.17","10.3.240.20","10.3.240.21"]
            name=["SZNS-KJY4F-ACS-05#","SZNS-KJY4F-ACS-06#","SZNS-KJY4F-ACS-08#","SZNS-KJY9F-ACS-11#","SZNS-KJY9F-ACS-12#"]
            stat_time=time.time()
            stru_time=time.localtime(stat_time)
            strf_time=time.strftime("%Y-%m-%d")
            for i in range(0,len(ip)):
                    child=pexpect.spawn('ssh fumy@%s'%ip[i])
                    fout=open('/root/switch_check/%s.txt'%(name[i][:-1]),'wb+')
                    child.logfile = fout
                    if ip[i]=="10.3.240.21":
                            child.expect("fumy@10.3.240.21's password:")
                    else:
                            child.expect('password: ')
                    child.sendline("你自己的密码")
                    child.expect("%s"%name[i])
                    child.sendline("sh env power")
                    child.expect("%s"%name[i])
                    child.sendline("show process cpu | in CPU utilization")
                    child.expect("%s"%name[i])
                    child.sendline("sh version | in uptime")
                    child.expect("%s"%name[i])
                    child.sendline("show processes memory | in Used")
                    child.expect("%s"%name[i])
                    child.sendline("sh env fan")
                    child.expect("%s"%name[i])
                    child.sendline("sh log | in Console logging")
                    child.expect("%s"%name[i])
                    child.sendline("exit")
                    time.sleep(3)
    
            file_list=os.listdir("/root/switch_check")
    
            with open("/root/switch_check/%s"%file_list[0]) as f1:
                    for i in f1:
                            if "POWER" in i:
                                    power1=i[8:].strip()
                            if "CPU utilization" in i:
                                    cpu1=i[72:].strip()
                            if "%s uptime is"%file_list[0][:-4] in i:
                                    uptime1="".join(i[27:].strip().split(","))
                            if "Processor Pool Total:" in i:
                                    memory1="%.2f%%"%((int(i[38:50].strip())/int(i[21:33].strip()))*100)
                            if "FAN is" in i:
                                    fan1=i[6:].strip()
                            if "level debugging" in i:
                                    log1=i[37:43].strip()
    
            with open("/root/switch_check/%s"%file_list[1]) as f2:
                    for i in f2:
                            if "POWER" in i:
                                    power2=i[8:].strip()
                            if "CPU utilization" in i:
                                    cpu2=i[72:].strip()
                            if "%s uptime is"%file_list[1][:-4] in i:
                                    uptime2="".join(i[27:].strip().split(","))
                            if "Processor Pool Total:" in i:
                                    memory2="%.2f%%"%((int(i[38:50].strip())/int(i[21:33].strip()))*100)
                            if "FAN is" in i:
                                    fan2=i[6:].strip()
                            if "level debugging" in i:
                                    log2=i[37:43].strip()
    
            with open("/root/switch_check/%s"%file_list[2]) as f3:
                    for i in f3:
                            if "POWER" in i:
                                    power3=i[8:].strip()
                            if "CPU utilization" in i:
                                    cpu3=i[72:].strip()
                            if "%s uptime is"%file_list[2][:-4] in i:
                                    uptime3="".join(i[27:].strip().split(","))
                            if "Processor Pool Total:" in i:
                                    memory3="%.2f%%"%((int(i[38:50].strip())/int(i[21:33].strip()))*100)
                            if "FAN is" in i:
                                    fan3=i[6:].strip()
                            if "level debugging" in i:
                                    log3=i[37:43].strip()
    
            with open("/root/switch_check/%s"%file_list[3]) as f4:
                    for i in f4:
                            if "POWER" in i:
                                    power4=i[24:].strip()
                            if "CPU utilization" in i:
                                    cpu4=i[72:].strip()
                            if "%s uptime is"%file_list[3][:-4] in i:
                                    uptime4="".join(i[27:].strip().split(","))
                            if "Total: " in i:
                                    memory4="%.2f%%"%((int(i[21:29].strip())/int(i[6:14].strip()))*100)
                            if "FAN is" in i:
                                    fan4=i[6:].strip()
                            if "level debugging" in i:
                                    log4=i[37:45].strip()
    
            
            with open("/root/switch_check/%s"%file_list[4]) as f5:
                    for i in f5:
                            if "POWER" in i:
                                    power5=i[24:].strip()
                            if "CPU utilization" in i:
                                    cpu5=i[72:].strip()
                            if "%s uptime is"%file_list[4][:-4] in i:
                                    uptime5="".join(i[27:].strip().split(","))
                            if "Total: " in i:
                                    memory5="%.2f%%"%((int(i[21:29].strip())/int(i[6:14].strip()))*100)
                            if "FAN is" in i:
                                    fan5=i[6:].strip()
                            if "level debugging" in i:
                                    log5=i[37:44].strip()
    
            workbook = xlwt.Workbook(encoding = 'utf-8')
            cisco = workbook.add_sheet('深圳网络设备巡检')
    
            style = xlwt.XFStyle()
            pattern = xlwt.Pattern()
            pattern.pattern = xlwt.Pattern.SOLID_PATTERN
            pattern.pattern_fore_colour = xlwt.Style.colour_map['red']
            style.pattern = pattern
            borders = xlwt.Borders()
            borders.left = 1
            borders.right = 1
            borders.top = 1
            borders.bottom = 1
            style.borders = borders 
            al = xlwt.Alignment()
            al.horz = 0x02      
            al.vert = 0x01      
            style.alignment = al
    
            style1 = xlwt.XFStyle()
            borders = xlwt.Borders()
            borders.left = 1
            borders.right = 1
            borders.top = 1
            borders.bottom = 1
            style1.borders = borders
            al = xlwt.Alignment()
            al.horz = 0x02      
            al.vert = 0x01      
            style1.alignment = al
    
            style3 = xlwt.XFStyle()
            borders = xlwt.Borders()
            borders.left = 1
            borders.right = 1
            borders.top = 1
            borders.bottom = 1
            style3.borders = borders
            al = xlwt.Alignment()
            al.horz = 0x02      
            al.vert = 0x01      
            style3.alignment = al
    
            first_col=cisco.col(0)
            sec_col=cisco.col(1)
            thr_col=cisco.col(2)
            for_col=cisco.col(3)
            first_col.width=200*25
            sec_col.width=120*25
            thr_col.width=120*25
            for_col.width=320*25
    
            cisco.write(0, 0,'设备名称',style)
            cisco.write(0,1, '管理地址',style)
            cisco.write(0,2, '检查项',style)
            cisco.write(0,3, '检查结果',style)
            cisco.write_merge(1,6,0,0,'%s'%file_list[0][:-4],style3)
            cisco.write_merge(1,6,1,1,'%s'%ip[0],style3)
            cisco.write(1,2, '电源状态',style1)
            cisco.write(2,2, 'cpu使用率',style1)
            cisco.write(3,2, '运行时间',style1)
            cisco.write(4,2, '内存使用率',style1)
            cisco.write(5,2, '风扇状态',style1)
            cisco.write(6,2, '日志条目',style1)
            cisco.write(1,3, power1,style3)
            cisco.write(2,3, cpu1,style3)
            cisco.write(3,3, uptime1,style3)
            cisco.write(4,3, memory1,style3)
            cisco.write(5,3, fan1,style3)
            cisco.write(6,3, log1,style3)
    
            cisco.write_merge(7,12,0,0,'%s'%file_list[1][:-4],style3)
            cisco.write_merge(7,12,1,1,'%s'%ip[1],style3)
            cisco.write(7,2, '电源状态',style1)
            cisco.write(8,2, 'cpu使用率',style1)
            cisco.write(9,2, '运行时间',style1)
            cisco.write(10,2, '内存使用率',style1)
            cisco.write(11,2, '风扇状态',style1)
            cisco.write(12,2, '日志条目',style1)
            cisco.write(7,3, power2,style3)
            cisco.write(8,3, cpu2,style3)
            cisco.write(9,3, uptime2,style3)
            cisco.write(10,3, memory2,style3)
            cisco.write(11,3, fan2,style3)
            cisco.write(12,3, log2,style3)
    
            cisco.write_merge(13,18,0,0,'%s'%file_list[2][:-4],style3)
            cisco.write_merge(13,18,1,1,'%s'%ip[2],style3)
            cisco.write(13,2, '电源状态',style1)
            cisco.write(14,2, 'cpu使用率',style1)
            cisco.write(15,2, '运行时间',style1)
            cisco.write(16,2, '内存使用率',style1)
            cisco.write(17,2, '风扇状态',style1)
            cisco.write(18,2, '日志条目',style1)
            cisco.write(13,3, power3,style3)
            cisco.write(14,3, cpu3,style3)
            cisco.write(15,3, uptime3,style3)
            cisco.write(16,3, memory3,style3)
            cisco.write(17,3, fan3,style3)
            cisco.write(18,3, log3,style3)
    
            cisco.write_merge(19,24,0,0,'%s'%file_list[3][:-4],style3)
            cisco.write_merge(19,24,1,1,'%s'%ip[3],style3)
            cisco.write(19,2, '电源状态',style1)
            cisco.write(20,2, 'cpu使用率',style1)
            cisco.write(21,2, '运行时间',style1)
            cisco.write(22,2, '内存使用率',style1)
            cisco.write(23,2, '风扇状态',style1)
            cisco.write(24,2, '日志条目',style1)
            cisco.write(19,3, power4,style3)
            cisco.write(20,3, cpu4,style3)
            cisco.write(21,3, uptime4,style3)
            cisco.write(22,3, memory4,style3)
            cisco.write(23,3, fan4,style3)
            cisco.write(24,3, log4,style3)
    
            cisco.write_merge(25,30,0,0,'%s'%file_list[4][:-4],style3)
            cisco.write_merge(25,30,1,1,'%s'%ip[4],style3)
            cisco.write(25,2, '电源状态',style1)
            cisco.write(26,2, 'cpu使用率',style1)
            cisco.write(27,2, '运行时间',style1)
            cisco.write(28,2, '内存使用率',style1)
            cisco.write(29,2, '风扇状态',style1)
            cisco.write(30,2, '日志条目',style1)
            cisco.write(25,3, power5,style3)
            cisco.write(26,3, cpu5,style3)
            cisco.write(27,3, uptime5,style3)
            cisco.write(28,3, memory5,style3)
            cisco.write(29,3, fan5,style3)
            cisco.write(30,3, log5,style3)
    
            workbook.save('SZ_NDC_%s.xls'%strf_time)
    
            os.system("mail -a /root/python/SZ_NDC_%s.xls -s check_test 你的邮箱 < /root/python/mail.txt "%strf_time)
    
            os.system("find /root/python/ -type f -mtime +15 -name 'SZ_NDC_*'|xargs \rm -f")
    
    cisco_check()

    mail.txt中的内容即邮件内容:

    各位好:

     

        巡检结果详情请看附件。

     

     

     

     

        ps:本邮件由系统自动发送,如有任何问题请联系***

     

     

         Best Wishes

    邮件配置

    /etc/mail.rc

    set from=邮箱地址 smtp=邮箱服务器 smtp-auth-user=邮箱用户名 smtp-auth-password=密码 smtp-auth=login

    定时任务

    crontab -e

    00 17 * * 5 /usr/bin/python3 /root/python/switch_check.py >/dev/null 2>&1 #每周五下午5点巡检

    最终效果

     

    转载于:https://www.cnblogs.com/fumy/p/11418829.html

    展开全文
  • python读取交换机配置做配置备份

    千次阅读 2019-09-01 14:17:07
    通常情况交换机一般会开启telnet或ssh,单独到每个交换机上不一定开启了ftp,所以还是拿常用的来做备份比较方便 python版本要求2.7 要求安装 paramiko包 主函数mainRun.py #!/usr/bin/python # -*- coding: UTF...

    通常情况交换机一般会开启telnet或ssh,单独到每个交换机上不一定开启了ftp,所以还是拿常用的来做备份比较方便

    python版本要求2.7

    要求安装 paramiko包

    主函数mainRun.py

    #!/usr/bin/python
    # -*- coding: UTF-8 -*-
    
    import paramiko
    import os, sys
    import json
    import time
    import telnetlib
    
    
    def sshconfig(ip, port, username, password, cmd, PS1, isNeedEnableMode, enablePassword):
        # 实例化SSHClient
        client = paramiko.SSHClient()
        # 自动添加策略,保存服务器的主机名和密钥信息
        client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        # 连接SSH服务端,以用户名和密码进行认证
        client.connect(hostname=ip, username=username, password=password, look_for_keys=False)
        chan = client.invoke_shell()
        chan.settimeout(9000)
    
        # 获取登陆后的消息
        welcomeinfo = ''
        while True:
            line = chan.recv(4096)
            welcomeinfo += line
            if (PS1 is not None) & (len(PS1) > 0):
                isFindPS1 = False;
                for i in range(len(PS1)):
                    if PS1[i] in line:
                        isFindPS1 = True
                if isFindPS1 == True:
                    break;
        print welcomeinfo
    
        if isNeedEnableMode == "1":
            chan.send('enable' + '\n')
            chan.send(enablePassword + '\n')
            # 获取特权后的消息
            enableInfo = ''
            while True:
                line = chan.recv(4096)
                enableInfo += line
                if (PS1 is not None) & (len(PS1) > 0):
                    isFindPS1 = False;
                    for i in range(len(PS1)):
                        if PS1[i] in line:
                            isFindPS1 = True
                    if isFindPS1 == True:
                        break;
            print enableInfo
    
        chan.send(cmd + '\n')
        result = ''
        # more交互处理
        more = '-- More --'
        more2 = '--More--'
        more3 = '<--- More --->'
        more4 = '-- More --'
        #  循环获取数据
        while True:
            line = chan.recv(4096)
            result += line
            if (more in line) | (more2 in line) | (more3 in line) | (more4 in line):
                chan.send(" ")
                continue;
            if (PS1 is not None) & (len(PS1) > 0):
                isFindPS1 = False;
                for i in range(len(PS1)):
                    if PS1[i] in line:
                        isFindPS1 = True
                if isFindPS1 == True:
                    break;
    
        print result
        return result
    
    def telnetconfig(ip, port, username, password, cmd, PS1, isNeedEnableMode, enablePassword):
        # 连接Telnet服务器
        tn = telnetlib.Telnet(ip, port=23, timeout=10)
        tn.set_debuglevel(2)
        # 处理登录
        # 输入登录用户名
        tn.read_until('Username:')
        tn.write(username.encode('ascii') + '\n')
    
        # 输入登录密码
        tn.read_until('Password:')
        tn.write(password.encode('ascii') + '\n')
    
        time.sleep(2)
    
        # 获取登陆后的消息
        welcomeinfo = ""
        while True:
            line = tn.read_very_eager().encode("ascii")
            welcomeinfo += line
            if (PS1 is not None) & (len(PS1) > 0):
                isFindPS1 = False;
                for i in range(len(PS1)):
                    if PS1[i] in line:
                        isFindPS1 = True
                if isFindPS1 == True:
                    break;
        print welcomeinfo
    
        #处理特权密码
        if isNeedEnableMode == "1":
            tn.write('enable'.encode('ascii') + '\n')
            tn.write(enablePassword.encode('ascii') + '\n')
            time.sleep(2)
            # 获取特权后的消息
            enableInfo = ''
            while True:
                line = tn.read_very_eager().encode("ascii")
                enableInfo += line
                if (PS1 is not None) & (len(PS1) > 0):
                    isFindPS1 = False;
                    for i in range(len(PS1)):
                        if PS1[i] in line:
                            isFindPS1 = True
                    if isFindPS1 == True:
                        break;
            print enableInfo
    
        tn.write(cmd.encode('ascii') + '\n')
        time.sleep(2)
        result = ''
        # more交互处理
        more = '-- More --'
        more2 = '--More--'
        more3 = '<--- More --->'
        more4 = '-- More --'
        #  循环获取数据
        while True:
            line = tn.read_very_eager().encode("ascii")
            result += line
            if (more in line) | (more2 in line) | (more3 in line) | (more4 in line):
                tn.write(" ".encode('ascii') )
                time.sleep(2)
                continue;
            if (PS1 is not None) & (len(PS1) > 0):
                isFindPS1 = False;
                for i in range(len(PS1)):
                    if PS1[i] in line:
                        isFindPS1 = True
                if isFindPS1 == True:
                    break;
    
        print result
        return result
    
        tn.close()  # tn.write('exit\n')
        return "aaa"
    
    def main():
        file = open("SwitchConfig.json", "rb")
        fileJson = json.load(file)
        switch = fileJson["switch"]
        # print switch
        for i in range(len(switch)):
            print switch[i]
            if switch[i]["protocol"] == "ssh":
                result = sshconfig(switch[i]["ip"], switch[i]["port"], switch[i]["username"], switch[i]["password"],
                                   switch[i]["cmd"], switch[i]["PS1"], switch[i]["isNeedEnableMode"],
                                   switch[i]["enablePassword"])
                fileName = switch[i]["fileName"]
                fileObject = open(fileName, 'w')
                fileObject.write(result)
                fileObject.close()
            if switch[i]["protocol"] == "telnet":
                result = telnetconfig(switch[i]["ip"], switch[i]["port"], switch[i]["username"], switch[i]["password"],
                                   switch[i]["cmd"], switch[i]["PS1"], switch[i]["isNeedEnableMode"],
                                   switch[i]["enablePassword"])
                fileName = switch[i]["fileName"]
                fileObject = open(fileName, 'w')
                fileObject.write(result)
    
        sys.exit(0)
    
    
    if __name__ == '__main__':
        main()
    

    交换机连接配置文件SwitchConfig.json

    {
    	"switch": [{
    		"ip": "192.168.5.1",
    		"port": "22",
    		"username": "cisco",
    		"password": "cisco123",
    		"protocol": "ssh",
    		"cmd": "show run",
    		"PS1": ["ASA5506X>","ASA5506X#"],
    		"desc": "ASA5506防火墙",
    		"isNeedEnableMode": "1",
    		"enablePassword": "cisco456",
    		"fileName": "asa5506X_192.168.5.1.txt"
    	},{
    		"ip": "192.168.5.254",
    		"port": "22",
    		"username": "huawei",
    		"password": "huawei123",
    		"protocol": "ssh",
    		"cmd": "display current-configuration",
    		"PS1": ["<Core-S5700>"],
    		"desc": "S5700核心交换机",
    		"isNeedEnableMode": "0",
    		"enablePassword": "",
    		"fileName": "core_s5700_192.168.5.254.txt"
    	},{
    		"ip": "192.168.10.1",
    		"port": "22",
    		"username": "cisco",
    		"password": "cisco123",
    		"protocol": "ssh",
    		"cmd": "show run",
    		"PS1": ["CME-2901>","CME-2901#"],
    		"desc": "CME-2901思科VOIP交换机",
    		"isNeedEnableMode": "1",
    		"enablePassword": "cisco456",
    		"fileName": "2901_CME_192.168.10.1.txt"
    	},{
    		"ip": "192.168.200.3",
    		"port": "22",
    		"username": "huawei",
    		"password": "huawei123",,
    		"protocol": "ssh",
    		"cmd": "display current-configuration",
    		"PS1": ["<POE-S5700>"],
    		"desc": "S5700POE交换机",
    		"isNeedEnableMode": "0",
    		"enablePassword": "",
    		"fileName": "poe_s5700_192.168.200.3.txt"
    	},{
    		"ip": "192.168.200.5",
    		"port": "22",
    		"username": "cisco",
    		"password": "cisco123",
    		"protocol": "ssh",
    		"cmd": "show run",
    		"PS1": ["POE-2960#"],
    		"desc": "2960交换机",
    		"isNeedEnableMode": "0",
    		"enablePassword": "",
    		"fileName": "2960_24poe_192.168.200.5.txt"
    
    	},{
    		"ip": "192.168.200.6",
    		"port": "23",
    		"username": "huawei",
    		"password": "huawei123",
    		"protocol": "telnet",
    		"cmd": "display current-configuration",
    		"PS1": ["<5600_6>"],
    		"desc": "5700交换机",
    		"isNeedEnableMode": "0",
    		"enablePassword": "",
    		"fileName": "5700_192.168.200.6.txt"
    	},{
    		"ip": "192.168.200.7",
    		"port": "22",
    		"username": "huawei",
    		"password": "huawei123",
    		"protocol": "ssh",
    		"cmd": "display current-configuration",
    		"PS1": ["<5700_7>"],
    		"desc": "5700交换机",
    		"isNeedEnableMode": "0",
    		"enablePassword": "",
    		"fileName": "5700_192.168.200.7.txt"
    	},{
    		"ip": "192.168.200.8",
    		"port": "23",
    		"username": "huawei",
    		"password": "huawei123",
    		"protocol": "telnet",
    		"cmd": "display current-configuration",
    		"PS1": ["<5700_8>"],
    		"desc": "5700交换机",
    		"isNeedEnableMode": "0",
    		"enablePassword": "",
    		"fileName": "5700_192.168.200.8.txt"
    	}]
    }

    目前这个程序保证用户名和密码对的情况下,还是可用的,没做多少容错处理,后续再进行优化

    等这个优化完,后续考虑加上配置变更检测,邮件通知,oss文件上传同步功能。

     

    update20190905:完成差不多了,码云gitee地址:https://gitee.com/gsls200808/Switch-Configuration-Backup-and-Change-Detection

    展开全文
  • 基于Python交换机实时监控系统的设计与实现.pdf
  • python-交换机巡检自动化 ​ 因为了解到python可以实现自动化的巡检功能,所以开始学习了《Python编程 从入门到实践》。通过一段时间的学习,将这本书的前11章看完,并开始搜索交换机巡检的相关模板,发现别人写的...

    python-交换机巡检自动化

    ​ 因为了解到python可以实现自动化的巡检功能,所以开始学习了《Python编程 从入门到实践》。通过一段时间的学习,将这本书的前11章看完,并开始搜索交换机巡检的相关模板,发现别人写的代码完全看不懂,很多模块,根本看不懂模块。经过一段时间的研究,要巡检,得学会以下几个模块:time、os、Netmiko、xlwt、re。
    关于交换机的交互模块,有些大神用的是pexpect模块,使用 pexpect.spawn.sendline() 来发送交换机的命令和 pexpect.swapn.expect() 来验证输出是否符合要求。而我这次所使用的就是 Netmiko
    我从开始学习到能ctrl+v出自己想要的脚本的过程如下:

    《Python编程 从入门到实践》——百度大神的脚本——了解大神脚本中模块的功能——根据需求自己写脚本

    接下来我们开始了解编写脚本,所需要了解的模块吧

    第一章、各模块介绍

    1、time模块——生成时间相关

    import time
    >>> res = time.strftime("%Y-%m-%d %H:%M:%S",time.localtime())
    >>> print(res)
    2021-04-15 18:53:20
    
    >>> res = time.strftime("%Y%m%d",time.localtime())
    >>> print(res)
    20210415
    

    2、os模块的使用——创建目录

    因为open模块只能创建文件,目录需要os模块来创建

    import os
    if not os.path.isdir("machine_learning"): 	#判定如何没有这个目录,就创建
        os.makedirs("machine_learning")			#创建
    

    3、Netmiko-SSH巡检

    通过ssh,巡检h3c的交换机。关键模块是ConnectHandler。

    #!/usr/bin/python3
    #H3c交换机
    from netmiko import ConnectHandler
    
    '''定义交换机,包括类型,密码,ip,主机名'''
    ip_list = [
        ['交换机的sysname','交换机的管理ip'],
    ]
    
    #这里定义了ssh要用到的参数
    SW = {
        'device_type':'hp_comware',     #设备类型是netmiko预定义好的,现在用hp_comware是h3c的
        'username':'admin',				
        'ip':'',
        'password':"xxxxxx"
    }
    '''定义结束'''
    
    '''交换机交互'''
    for ip_item in ip_list:
        SW['ip'] = ip_item[1]
        connect = ConnectHandler(**SW)
        print(log_time + 'Successfully connected to ' + ip_item[0])
        output = connect.send_command('system view')
        iproute = connect.send_command("display ip routing-table")
       	print(output) 				#验证	
        print(iproute) 				#验证
    '''交换结束'''
    

    3.2、Netmiko-telnet巡检

    telnet与ssh的区别应该就在于,device_type中尾部添加_telnet,用的是Netmiko,而ssh用的是ConnectHandler。

    我们的telnet分为h3c和cisco。

    H3C

    from netmiko import Netmiko
    
    '''定义交换机,包括类型,密码,ip,主机名'''
    ip_list = [
        ['交换机的sysname','交换机的ip地址'],   #定义设备的用户名和管理地址
    ]
    SW = {
        'device_type':'hp_comware_telnet',					#设备类型是netmiko预定义好的
        'username':'admin',
        'ip':'',
        'password':"xxxxxx",	
    }
    '''完成定义'''
    
    '''与交换机交互'''
    for ip_item in ip_list:
        SW['ip'] = ip_item[1]
        connect = Netmiko(**SW)
        print(log_time + 'Successfully connected to ' + ip_item[0])
        config = connect.send_command('dis cur')
        fan = connect.send_command('dis fan')
        print(config) 	#验证一下值是不是想要的
        print(fan) 		#验证一下值是不是想要的
    

    cisco

    主要的不同是,cisco的telnet是需要enable的。

    from netmiko import Netmiko
    
    '''定义交换机,包括类型,密码,ip,主机名'''
    ip_list = [
        ['交换机的hostname','交换机的ip'],   #定义设备的用户名和管理地址
    ]
    SW = {
        'device_type':'cisco_iso_telnet',					#设备类型是netmiko预定义好的
        'username':'admin',
        'ip':'',
        'password':"xxxxxx",								#telnet的密码
        'secret':'xxxxx',									#enable的密码
    }
    '''完成定义'''
    
    '''与交换机交互'''
    for ip_item in ip_list:
        SW['ip'] = ip_item[1]
        connect = Netmiko(**SW)
        connect.enable()									#注意这个地方!cisco是这样enable的
        print(log_time + 'Successfully connected to ' + ip_item[0])
        config = connect.send_command('shun run')
        cpu = connect.send_command('sh process cpu')
        print(config) 	#验证一下值是不是想要的
        print(fan) 		#验证一下值是不是想要的
    

    4、xlwt模块-创建excel

    import xlwt
    workbook = xlwt.Workbook()
    worksheet = workbook.add_sheet('巡检报告第一次') #创建worksheet
    worksheet.write(0,0,label = '设备名称')			#对A1添加内容
    worksheet.write(0,1,label = '属性')				#对B1添加内容
    worksheet.write(0,2,'值')						#对C2添加内容
    workbook.save('巡检报告生成.xls')					#保存到excel,如果没有会创建。
    

    在这里插入图片描述

    5、re模块——正则表达式,截取想要的字段。

    截取a-b之间的字符串:不包括ab

    #注意有两种形式。一个匹配到第一个b,一个是匹配到最后一个b。
    import re
    number = "a123b456b" 
    
    print(re.findall(r"a(.+?)b", number)) #注意!匹配到第一个b。
    #输出['123']
    
    print(re.findall(r"a(.+)b", number)) #这个是匹配到最后一个b
    #输出['123b456']
    
    

    另外一种正则表达式的使用形式

    import re
    number = "a123b456b"
    
    pattern = re.complie("a(.+)b")
    print(pattern.findall(number))
    #输出['123b456']
    

    从a开始截取到b为止: 包括ab

    import re
    number = "a123b456b" 
    
    print(re.findall(r"a.+?b", number)) #注意!匹配到第一个b。
    #输出['a123b']
    
    print(re.findall(r"a.+b", number)) #这个是匹配到最后一个b
    #输出['a123b456b']
    

    第二章、巡检脚本介绍

    1、巡检并记录下txt

    这里只自定义了一个h3c的交换机巡检模块,而cisco的大同小异,差别在于 ”使用不同的netmiko子模块“、“定义交换机时多一个enable密码”、”多了enable模块(在第一章—3.2——cisco中有说明))“

    #!/usr/bin/python3
    #H3c交换机
    '''-------模块导入--------'''
    import time
    from netmiko import ConnectHandler
    from netmiko import Netmiko
    import os
    import re
    import xlwt
    '''--------模块导入结束--------'''
    
    '''----------------------创建文件夹-------------------------'''
    time_str = time.strftime('%Y_%m_%d', time.localtime())
    path = "D:\\Seafile\\2021年农林维护\\3-巡检"
    title = "%s"%time_str
    new_path = os.path.join(path, title) #创建基于日期命名的文件夹
    log_path = "%s\\巡检文件"%new_path	
    config_path = "%s\\配置文件备份"%new_path
    if not os.path.isdir(new_path):
        os.makedirs(new_path)
    if not os.path.isdir(log_path):
        os.makedirs(log_path)
    if not os.path.isdir(config_path):
        os.makedirs(config_path)
    '''----------------------------创建文件夹结束------------------'''
    
    '''-------------------和学校h3c交换机交互,并保留文本用于后期筛选数据的模块-----------'''
    def h3c_ssh_v7(sysname,ipadd):
        ip_list = [
            [sysname,ipadd],
        ]
        SW = {
            'device_type':'hp_comware',
            'username':'用户名',
            'ip':'',
            'password':"密码",
        }
        
        for ip_item in ip_list:
            SW['ip'] = ip_item[1]
            connect = ConnectHandler(**SW)
            print(time_str + 'Successfully connected to ' + ip_item[0])
            config = connect.send_command('dis current-configuration')
            fan = connect.send_command('dis fan')
            
            '''-----这里我们只需要dis process cpu第一行的资料,进行预筛查----'''
            cpu = connect.send_command('dis process cpu')
            cpu = cpu.split('\n')	#cpu show出来时纯字符串,我用split配合换行符分割。
            cpu = cpu[0]			#分割好只取第一行
            '''-----------------------cpu内容预筛选结束-------------------'''
            
            power = connect.send_command('dis power')
            manager_ip = connect.send_command('dis ip int vlan 1 brief')
            device = connect.send_command('dis device | exclude NONE')
            
            '''-------------------同样时预筛查只需要前四行内容-----------------------'''
            version = connect.send_command('dis version')
            version = version.split('\n')
            version = '\n'.join(version[0:4]) #因为version[0:4]出来的是一个列表,所以使用join,将列表内容拼接成字符串。
            '''-------------------------预筛查结束--------------------------------'''
        
            config_fo = open('%s\\%s-%s_config.txt'%(config_path,ip_item[0],ip_item[1]),'w',encoding='utf-8')#创建配置备份,文件名时sysname-ipadd的格式。记住这里一定要加入encoding=‘utf-8',不然有些h3c设备可能会报错。
            fo = open('%s\\%s-%s.txt'%(log_path,ip_item[0],ip_item[1]),'w') #创建巡检的文件。存放巡检时候产生的数据
            config_fo.write(config)
            if cpu:									#如果cpu有数据存在
                fo.write(cpu)						#把cpu的巡检结果写入巡检文件 以下类似
            fo.write('\n')							#换行,让文本看的清楚些用的。以下大概就这些消息,不逐一说了
            fo.write('\n')
            if fan:
                fo.write(fan)
            fo.write('\n')
            fo.write('\n')
            if power:
                fo.write(power)
            fo.write('\n')
            fo.write('\n')
            if version:
                fo.write(version)
            fo.write('\n')
            fo.write('\n')
            if manager_ip:
                fo.write(manager_ip)
            fo.write('\n')
            fo.write('\n')
            if device:
                fo.write(device)
                
    h3c_ssh_v7('设备的sysname','设备的ip地址')记得调用函数
    """------------------------------------巡检备份结束-------------------------------------------------------"""
    

    2、分析文件并写入excel报告

    因为楼宇,核心,服务器核心所生成的巡检文件有很大的不同所以我选择了分开写。

    这里我只列了我们核心交换机的数据抓取。

    """-------------------承接上面的代码(因为要用到导入的模块和变量))---生成报告-------------------------------"""
    y = 1 #这个是用来记录我的excel写到了哪一行的
    def h3c_core_report(hostname,ipadd):
            file = open('%s\\%s-%s.txt'%(log_path,hostname,ipadd))
            listlist=file.readlines()
            i=1 #注意:在下面'''分析提取数据并提取'''代码块最后有个i += 1 用于计数。当“我要抓取的数据在我能匹配到数据行的下一行。”的时候就会用到了。
           
            
    '''------------------------分析数据并提取--------------------------------------------'''
            for line in listlist:
                if 'CPU utilization' in line:
                        pattern = re.compile('5.+%')	#正则匹配的匹配规则
                        cpu_use_list = pattern.findall(line) #使用规则抓出数据,下面的代码都是大同小异的抓取
                        for cpu_use in cpu_use_list:    #因为抓出的数据是列表,用for循环转换为字符。其实可以用cpu_use_list[0]。
                                print(cpu_use)
                if 'weeks' in line:
                        run_time_list = re.findall("uptime is(.+?)\n",line)
                        for run_time in run_time_list:
                                print(run_time.strip())
                if 'Chassis 1' in line:     #因为用了H3C的IRF设备,有多行Chassis 1,显示chassis1上例如风扇、电源的状态
                        if 'Fan' in listlist[i]: #和上一行执行“与”操作,匹配到就抓取数据。
                                pattern = re.compile(':(.+)\n')
                                chassis_1_fan_list = pattern.findall(listlist[i]) #这个就是抓取匹配行的下一行
                                for chassis_1_fan in chassis_1_fan_list:
                                        chassis_1_fan = chassis_1_fan.strip()
                                        print(chassis_1_fan)
                        if 'Power' in listlist[i]: #和chassis 1行进行“与”操作,匹配就抓取需要的数据
                                pattern = re.compile(':(.+)\n')
                                chassis_1_power_0_state_list = pattern.findall(listlist[i])
                                for chassis_1_power_0_state in chassis_1_power_0_state_list:
                                        chassis_1_power_0_state = chassis_1_power_0_state.strip()
                                        print(chassis_1_power_0_state)
    
                                chassis_1_power_1_state_list = pattern.findall(listlist[i+1])
                                for chassis_1_power_1_state in chassis_1_power_1_state_list:
                                        chassis_1_power_1_state = chassis_1_power_1_state.strip()
                                        print(chassis_1_power_1_state)
                                        
                                chassis_1_power_2_state_list = pattern.findall(listlist[i+2])
                                for chassis_1_power_2_state in chassis_1_power_2_state_list:
                                        chassis_1_power_2_state = chassis_1_power_2_state.strip()
                                        print(chassis_1_power_2_state)
                                        
                                chassis_1_power_3_state_list = pattern.findall(listlist[i+3])
                                for chassis_1_power_3_state in chassis_1_power_3_state_list:
                                        chassis_1_power_3_state = chassis_1_power_3_state.strip()
                                        print(chassis_1_power_3_state)
                                        
                                chassis_1_power_4_state_list = pattern.findall(listlist[i+4])
                                for chassis_1_power_4_state in chassis_1_power_4_state_list:
                                        chassis_1_power_4_state = chassis_1_power_4_state.strip()
                                        print(chassis_1_power_4_state)
    
                                chassis_1_power_5_state_list = pattern.findall(listlist[i+5])
                                for chassis_1_power_5_state in chassis_1_power_5_state_list:
                                        chassis_1_power_5_state = chassis_1_power_5_state.strip()
                                        print(chassis_1_power_5_state)
    
                if 'Chassis 2' in line: #这里就是抓取chassis 2上的数据
                        if 'Fan' in listlist[i]:
                                pattern = re.compile(':(.+)\n')
                                chassis_2_fan_list = pattern.findall(listlist[i])
                                for chassis_2_fan in chassis_2_fan_list:
                                        chassis_2_fan = chassis_2_fan.strip()
                                        print(chassis_2_fan)
                        if 'Power' in listlist[i]:
                                pattern = re.compile(':(.+)\n')
                                chassis_2_power_0_state_list = pattern.findall(listlist[i])
                                for chassis_2_power_0_state in chassis_2_power_0_state_list:
                                        chassis_2_power_0_state = chassis_2_power_0_state.strip()
                                        print(chassis_2_power_0_state)
    
                                chassis_2_power_1_state_list = pattern.findall(listlist[i+1])
                                for chassis_2_power_1_state in chassis_2_power_1_state_list:
                                        chassis_2_power_1_state = chassis_2_power_1_state.strip()
                                        print(chassis_2_power_1_state)
                                        
                                chassis_2_power_2_state_list = pattern.findall(listlist[i+2])
                                for chassis_2_power_2_state in chassis_2_power_2_state_list:
                                        chassis_2_power_2_state = chassis_2_power_2_state.strip()
                                        print(chassis_2_power_2_state)
                                        
                                chassis_2_power_3_state_list = pattern.findall(listlist[i+3])
                                for chassis_2_power_3_state in chassis_2_power_3_state_list:
                                        chassis_2_power_3_state = chassis_2_power_3_state.strip()
                                        print(chassis_2_power_3_state)
                                        
                                chassis_2_power_4_state_list = pattern.findall(listlist[i+4])
                                for chassis_2_power_4_state in chassis_2_power_4_state_list:
                                        chassis_2_power_4_state = chassis_2_power_4_state.strip()
                                        print(chassis_2_power_4_state)
    
                                chassis_2_power_5_state_list = pattern.findall(listlist[i+5])
                                for chassis_2_power_5_state in chassis_2_power_5_state_list:
                                        chassis_2_power_5_state = chassis_2_power_5_state.strip()
                                        print(chassis_2_power_5_state)
    
                if '1/0' in line: #抓取板卡信息
                        slot1_1_list = line.split()  #为了抓取状态值使用的手段,主要是将字段转成列表,然后再提取列表中的字符,以下其他板卡形式相同。
                        slot1_1_state = slot1_1_list[2]
                        print(f"1{slot1_1_state}")
                if '1/4    LSUM1SUPC0' in line:
                        slot1_4_list = line.split()
                        slot1_4_state = slot1_4_list[2]
                        print(f"4{slot1_1_state}")
                if '1/5    LSUM1SUPC0' in line:
                        slot1_5_list = line.split()
                        slot1_5_state = slot1_5_list[2]
                        print(slot1_5_state)
                if '1/7    LSUM2TGS16SF0' in line:
                        slot1_7_list = line.split()
                        slot1_7_state = slot1_7_list[2]
                        print(slot1_7_state)
                if '1/9    LSUM2GT24PTSSE0' in line:
                        slot1_9_list = line.split()
                        slot1_9_state = slot1_9_list[2]
                        print(slot1_9_state)
                if '1/10   LSU1FAB08B0' in line:
                        slot1_10_list = line.split()
                        slot1_10_state = slot1_10_list[2]
                        print(f"10{slot1_10_state}")
                if '1/11   LSU1FAB08B0' in line:
                        slot1_11_list = line.split()
                        slot1_11_state = slot1_11_list[2]
                        print(slot1_11_state)
                if '1/12   LSU1FAB08B0' in line:
                        slot1_12_list = line.split()
                        slot1_12_state = slot1_12_list[2]
                        print(slot1_12_state)
                if '1/13   LSU1FAB08B0' in line:
                        slot1_13_list = line.split()
                        slot1_13_state = slot1_13_list[2]
                        print(slot1_13_state)
    
                if '2/0    LSUM2GT48SE0' in line:
                        slot2_1_list = line.split()
                        slot2_1_state = slot2_1_list[2]
                        print(slot2_1_state)
                if '2/4    LSUM1SUPC0' in line:
                        slot2_4_list = line.split()
                        slot2_4_state = slot2_4_list[2]
                        print(slot2_4_state)
                if '2/5    LSUM1SUPC0' in line:
                        slot2_5_list = line.split()
                        slot2_5_state = slot2_5_list[2]
                        print(slot2_5_state)
                if '2/7    LSUM2TGS16SF0' in line:
                        slot2_7_list = line.split()
                        slot2_7_state = slot2_7_list[2]
                        print(slot2_7_state)
                if '2/9    LSUM2GT24PTSSE0' in line:
                        slot2_9_list = line.split()
                        slot2_9_state = slot2_9_list[2]
                        print(slot2_9_state)
                if '2/10   LSU1FAB08B0' in line:
                        slot2_10_list = line.split()
                        slot2_10_state = slot2_10_list[2]
                        print(slot2_10_state)
                if '2/11   LSU1FAB08B0' in line:
                        slot2_11_list = line.split()
                        slot2_11_state = slot2_11_list[2]
                        print(slot2_11_state)
                if '2/12   LSU1FAB08B0' in line:
                        slot2_12_list = line.split()
                        slot2_12_state = slot2_12_list[2]
                        print(slot2_12_state)
                if '2/13   LSU1FAB08B0' in line:
                        slot2_13_list = line.split()
                        slot2_13_state = slot2_13_list[2]
                        print(slot2_13_state)
    
    
                i += 1 #用来计数的。
    '''-------------------------分析和提取数据结束----------------------------------'''
    
    '''-----------------------开始写入excle数据------------------------------------'''
            x = 0    #用来计算我这个交换机用了多少行。主要为合并单元格服务的
            global y #计算整个excel使用了多少行。主要帮助程序从那里一行开始写入,合并单元格的时候也会用到。
            worksheet.write(y,1,label = '管理地址')
            worksheet.write(y,2,label = ipadd)
            y = y + 1
            x += 1
            if cpu_use:
                    worksheet.write(y,1,label = 'CPU使用率')
                    worksheet.write(y,2,cpu_use)
                    y = y + 1
                    x += 1
            if run_time:
                    worksheet.write(y,1,label = '运行时间')
                    worksheet.write(y,2,run_time)
                    y = y + 1
                    x += 1
            if slot1_1_state:
                    worksheet.write(y,1,"slot1_1")
                    worksheet.write(y,2,slot1_1_state)
                    y = y + 1
                    x += 1
            if slot1_4_state:
                    worksheet.write(y,1,"slot1_4")
                    worksheet.write(y,2,slot1_4_state)
                    y = y + 1
                    x += 1
            if slot1_5_state:
                    worksheet.write(y,1,"slot1_5")
                    worksheet.write(y,2,slot1_5_state)
                    y = y + 1
                    x += 1
            if slot1_7_state:
                    worksheet.write(y,1,"slot1_7")
                    worksheet.write(y,2,slot1_7_state)
                    y = y + 1
                    x += 1
            if slot1_9_state:
                    worksheet.write(y,1,"slot1_9")
                    worksheet.write(y,2,slot1_9_state)
                    y = y + 1
                    x += 1
            if slot1_10_state:
                    worksheet.write(y,1,"slot1_10")
                    worksheet.write(y,2,slot1_10_state)
                    y = y + 1
                    x += 1
            if slot1_11_state:
                    worksheet.write(y,1,"slot1_11")
                    worksheet.write(y,2,slot1_11_state)
                    y = y + 1
                    x += 1
            if slot1_12_state:
                    worksheet.write(y,1,"slot1_12")
                    worksheet.write(y,2,slot1_12_state)
                    y = y + 1
                    x += 1
            if slot1_13_state:
                    worksheet.write(y,1,"slot1_12")
                    worksheet.write(y,2,slot1_13_state)
                    y = y + 1
                    x += 1
            if slot1_1_state:
                    worksheet.write(y,1,"slot1_1")
                    worksheet.write(y,2,slot1_1_state)
                    y = y + 1
                    x += 1
            if slot1_4_state:
                    worksheet.write(y,1,"slot1_4")
                    worksheet.write(y,2,slot1_4_state)
                    y = y + 1
                    x += 1
            if slot1_5_state:
                    worksheet.write(y,1,"slot1_5")
                    worksheet.write(y,2,slot1_5_state)
                    y = y + 1
                    x += 1
            if slot1_7_state:
                    worksheet.write(y,1,"slot1_7")
                    worksheet.write(y,2,slot1_7_state)
                    y = y + 1
                    x += 1
            if slot1_9_state:
                    worksheet.write(y,1,"slot1_9")
                    worksheet.write(y,2,slot1_9_state)
                    y = y + 1
                    x += 1
            if slot1_10_state:
                    worksheet.write(y,1,"slot1_10")
                    worksheet.write(y,2,slot1_10_state)
                    y = y + 1
                    x += 1
            if slot1_11_state:
                    worksheet.write(y,1,"slot1_11")
                    worksheet.write(y,2,slot1_11_state)
                    y = y + 1
                    x += 1
            if slot1_12_state:
                    worksheet.write(y,1,"slot1_12")
                    worksheet.write(y,2,slot1_12_state)
                    y = y + 1
                    x += 1
            if slot1_13_state:
                    worksheet.write(y,1,"slot1_12")
                    worksheet.write(y,2,slot1_13_state)
                    y = y + 1
                    x += 1
            worksheet.write_merge(y-x,y-1,0,0,hostname)
            workbook.save('%s\\巡检报告生成.xls'%(log_path))
            print(y)         
            print(x)
    """-------------------------------------------写入结束--------------------------------------------------"""
            
    h3c_core_report('Dh_Tsg_1F_HeXin_S10508-V','10.27.0.1') #记得调用函数。
    """------------------------------------生成报告完成-------------------------------------------------------"""
    

    脚本执行后的结果:

    将上述的代码合并,在计算机任意位置执行,它就会自动生成一系列我们需要的文件。

    excel巡检报告结果如图:此图我还是手动调整过的,因为在生成excel的时候没有,我没有定义style文件(因为懒),但是具体xwlt是可以实现的。
    在这里插入图片描述

    展开全文
  • Python读取交换机配置

    2017-04-06 15:49:00
    我的第一个Python编码 import pexpect try: for host in open('HK5700IPs.txt','r').readlines(): print(host) #switchIP = host.strip('\\n') switchIP = host telnet...

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





    转载于:https://www.cnblogs.com/wintershen/p/6673828.html

    展开全文
  • 主要介绍了python批量修改交换机密码的示例,帮助大家更好的理解和使用python,感兴趣的朋友可以了解下
  • Python进行交换机信息抓取

    千次阅读 2018-10-26 15:05:23
    需求:登录交换机下指令对回传信息进行抓取写入 CSV文件 #encoding=utf-8 import telnetlib import re import datetime,os def do_telnet(HOST,USERNAME,PASSWORD): tn = telnetlib.Telnet(HOST, port=23, ...
  • 只要是交换机支持ftp都可以用此脚本进行备份,只需要改一下交换机配置文件的名称,不同厂家交换机备份文件名称不一样。同时需要交换机开启ftp
  • 主要介绍了python利用paramiko实现交换机巡检,帮助大家更好的理解和使用python,感兴趣的朋友可以了解下
  • 1.通过netmiko模块登录交换机,协议ssh,执行收集信息命令,保存至txt文件2.过滤txt文件中的内容,保存到excel,使用xlwt模块实现。.../usr/bin/python3#H3c交换机import timefrom netmiko import ConnectHandler...
  • 我在测试一项功能,使用python连接交换机(串口线COM口连接) 根据模块serial测试,数据无法传输到交换机交换机也无法提供数据给电脑,求各位指导,相同的方法即可,不一定需要serial模块 想用COM...
  • 原文地址... # encoding=utf-8 import paramiko import time client = paramiko.SSHClient() ...client.load_system_host_keys() ......
  • 为了快速生成有规律的VRF,写了一个python脚本,可以快速生成如下的VRF配置。 ip vpn-instance vpn0ipv4-family route-distinguisher 600:600vpn-target 600:600 both quit quit #!/usr/bin/python2.7 ...
  • 将之前Python写的批量管理配置交换机贴上来,供需要的网友提供一点借鉴,使用的是paramiko库: [root@zabbix609 python]# cat py-ssh2960-arg.py #!/usr/bin/env python import paramiko import time import ...
  • 你只需要一份配置模板,一列ip表。这个脚本会把模板刷到对应ip设备里。 适合网络人员,支持ssh登陆的交换机或者服务器。
  • 今天小编就为大家分享一篇使用python telnetlib批量备份交换机配置的方法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
  • 主要介绍了python代码 FTP备份交换机配置脚本实例解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
  • python 自动化获取交换机信息

    千次阅读 2019-01-26 11:54:03
    获取交换机信息,包括思科(Cisco)、博科(Brocade)、华为(Huawei)、华三(H3C)四个品牌。获取的信息包括:主机、内存、flash、固件版本(os_version)物理端口、逻辑端口(聚合口)、vlan、以及互联端mac和ip...

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 15,969
精华内容 6,387
关键字:

python交换机

python 订阅