zoukankan      html  css  js  c++  java
  • 交换机配置文件备份

    # coding: UTF-8
    import os
    import time
    from concurrent import futures
    
    
    HEADERS = {
        'Content-Type': 'application/json',
        'Accept': 'application/json',
    }
    
    def connect(host, username, password, **kwargs):
        client = None
        if Network.check_port(host, 23):
            print("{}: Try Use Telnet ".format(host))
            client = Network.DoTelnet(host, username, password, **kwargs)
        elif Network.check_port(host, 22):
            print("{}: Try Use SSH ".format(host))
            client = Network.DoSSH(host, username, password, **kwargs)
            if not client.login() and Network.check_port(host, 23):
                print("{}: Try Use Telnet ".format(host))
                client = Network.DoTelnet(host, username, password, **kwargs)
        else:
            print('{}: SSH 和 Telnet 端口都不通,请确认网络正常或端口是否被修改'.format(host))
        if client and client.login():
            return client
    
    def save_to_file(save_dir, file_name, content):
        try:
            if not os.path.exists(save_dir):
                os.makedirs(save_dir)
            conf_path = os.path.abspath(os.path.join(save_dir, file_name))
            with open(conf_path, 'w') as cf:
                cf.write(content)
            return conf_path
        except Exception as e:
            print('Error, 保存到文件失败, {}'.format(e))
    
    
    def switch_conf_bak(host, username, password, enable_passwd=None, **kwargs):
        global SUCCESS
        """支持cisco、 h3c 、huawei 交换机的配置文件备份"""
        client = connect(host, username, password, **kwargs)
        if not client:  # 连接失败退出
            print("Error, {} 连接失败".format(host))
            return
        if client.device_type in ['cisco']:
            conf_name = 'startup'
            code, out = client.run('show startup-config', 5)
            if code:
                if not enable_passwd:
                    print "Error, {}: 需要特权密码".format(host)
                    return
                if not client.enter_enable(enable_passwd):
                    return
                code, out = client.run('show running-config', 5)
                conf_name = 'running'
        elif client.device_type in ['ruijie']:
            code, out = client.run('show running-config', 5)
            conf_name = 'running'
            if code:
                if not enable_passwd:
                    print "Error, {}: 需要特权密码".format(host)
                    return
                if not client.enter_enable(enable_passwd):
                    return
                code, out = client.run('show running-config', 5)
        elif client.device_type in ['h3c', 'huawei']:
            conf_name = 'current'
            code, out = client.run('display current-configuration', 5)
            if code:
                if client.run('system-view')[0]:
                    print 'Error, {}: 进入特权模式失败'.format(host, client.device_type)
                    return False
                code, out = client.run('display current-configuration', 5)
        else:
            print 'Error, {}, 不支持的设备类型:{}'.format(host, client.device_type)
            return
        client.close()
    
        if not code:
            filename = '{}_{}_{}_{}.txt'.format(host, client.device_type, conf_name, time.strftime('%Y%m%d_%H%M%S'))
            conf = '
    '.join(out)
            print('{}: 获取配置成功, {} 字节'.format(host, len(conf)))
            file_path = save_to_file(save_path, filename, conf)
            if file_path:
                bak_path.append(file_path)
                print('{}: 保存到文件成功, {}'.format(host, file_path))
                SUCCESS += 1
            return file_path
        else:
            print "Error, {}: 命令错误,备份失败".format(host)
            print(out)
    
    
    if __name__ == '__main__':
        start_time = time.time()
        SUCCESS = 0
        save_path = '/tmp/switch_bak'
        bak_path = []
    
    
        hosts = [ip.strip() for ip in ips.split() if ip.strip()]
    
        # 多线程执行
        with futures.ThreadPoolExecutor(max_workers=15) as executor:
            for host in hosts:
                executor.submit(switch_conf_bak, host, username, password, enable_passwd)
    
        print('执行结束,总 {} ,成功 {}, 失败{}, 耗时 {}s'.format(len(hosts),
                SUCCESS, len(hosts) - SUCCESS, time.time() - start_time))
        bak_path = ','.join(bak_path)
        print(bak_path)
    

      

  • 相关阅读:
    解决拼团首页swiper组件手动轮播卡顿问题
    mac上charels抓包工具使用技巧
    加载图片优化(先用一张小图片做高斯模糊, 再加载大图)
    requirejs2读书笔记
    escape encodeURI encodeURIComponent区别
    js与cookie的domain和path之间的关系
    Oracle使用——数据泵导入导出数据库——impdp/expdp使用
    Oracle基础知识点——Oracle服务端和客户端
    Oracle使用——oracle11g安装——Oracle要求的结果: 5.0,5.1,5.2,6.0 6.1 之一 实际结果: 6.2
    Spring 学习——Spring AOP——AOP配置篇Advice(有参数传递)
  • 原文地址:https://www.cnblogs.com/slqt/p/10907386.html
Copyright © 2011-2022 走看看