H3C_Python_SSH_Config_Auto_2

  • 针对上一版的脚本进行改进
  • 增加嵌套一层 ‘ Try……finally: ’ ,代码执行末尾提示 “按任意键退出”
  • 修改代码中预定义的登陆账号密码为 input 和 getpass 手动输入
  • 修改文件当前目录为代码自动获取 os.getcwd()
  • 修改执行完成后显示 “A log file is available in……” 记录log路径
  • 想改多线程,threading 模块逻辑没搞清楚

两个脚本

01

# File: py_net.py
# Time: 2022/05/13 12:20:35
# Author: Kir
# Ver: 2.0
# Description: AutoOutput/SSH/Log

import time
from netmiko import ConnectHandler, NetMikoAuthenticationException, NetMikoTimeoutException
import os
import re
import msvcrt
import getpass

try:
    # 校验账户交给netmiko模块,仅输入
    login_user = input('Login:')
    login_pwd = getpass.getpass('Passwd:')
    # 时间格式蒸鹅心,冒号不能用做文件名字符
    time_str1 = time.strftime('%Y%m%d', time.localtime())
    time_str2 = time.strftime('%H%M%S', time.localtime())
    time_str3 = time.strftime('%H:%M:%S', time.localtime())
    # 获取当前工作目录
    path = os.getcwd()
    title = "%s" % time_str1
    # mkdir path & touch file
    new_path = os.path.join(path, title)
    config_path = "%s\\configuration_backup" % new_path
    if not os.path.isdir(new_path):
        os.makedirs(new_path)
    if not os.path.isdir(config_path):
        os.makedirs(config_path)
    # 创建日志文件,记录运行结果
    log_fo = open(
        '%s\\%s.log' % (config_path, time_str1),
        'a+',
        encoding='utf-8',
    )
    log_fo.write('\n' + "==========START TIME " + time_str3 + "=========" +
                 '\n')
    # 读取 ip_list.txt 里的 ip 地址
    ip_list = open('ip_list.txt', 'r', encoding='ascii')
    ip_addr = ip_list.readlines()
    ip_list.close()
    # display 命令
    cmd_list = open('cmd_list.txt', 'r', encoding='ascii')
    cmd_line = cmd_list.readlines()
    cmd_list.close()

    # 遍历 ip_addr 列表里面的 ip 进行连接
    for ip in iter(ip_addr):
        try:
            S5130 = {
                'device_type': 'hp_comware',
                'ip': ip,
                'username': login_user,
                'password': login_pwd,
            }

            net_connect = ConnectHandler(**S5130)
            # 禁用输出屏幕分屏
            screen_d = net_connect.send_command('screen-length disable')
            # current_time as part of filename
            time_str2 = time.strftime('%H%M%S', time.localtime())
            # sysname as part of fielname
            sysn = net_connect.send_command('dis cur | inc sysname')
            # split 空格分割回显内容
            sysn = re.split(r'[ ]+', sysn)
            sysn = sysn[2]
            # 创建文件, 格式为 sysname + time_str2
            config_fo = open('%s\\%s_%s_config.txt' %
                             (config_path, sysn, time_str2),
                             'a',
                             encoding='utf-8')
            time_str3 = time.strftime('%H:%M:%S', time.localtime())
            print(time_str1 + "_" + time_str3 + ' Successfully connected to ' +
                  ip)
            log_fo.write(time_str1 + "_" + time_str3 +
                         ' Successfully connected to ' + ip)
            for cmd in iter(cmd_line):
                # 发送 cmd
                cmd_result = net_connect.send_command(cmd)
                print(cmd)
                print(cmd_result)
                print(
                    '==================================================================='
                )
                config_fo.write(
                    '\n' +
                    '==================================================================='
                    + '\n' + cmd + '\n' + cmd_result)
            net_connect.disconnect()
            config_fo.close()
        except (EOFError, NetMikoTimeoutException):
            print('Can not connect to Device ' + ip)
            time_str3 = time.strftime('%H:%M:%S', time.localtime())
            log_fo.write(time_str1 + "_" + time_str3 +
                         ' Can not connect to Device ' + ip)
        except (EOFError, NetMikoAuthenticationException):
            print('username/password wrong! ' + ip)
            time_str3 = time.strftime('%H:%M:%S', time.localtime())
            log_fo.write(time_str1 + "_" + time_str3 +
                         ' username/password wrong! ' + ip)
    time_str4 = time.strftime('%H:%M:%S', time.localtime())
    log_fo.write('\n' + "==========END TIME " + time_str4 + "==========" +
                 '\n')

    log_fo.close()
    print('\n')
    print('A log file is available in ' + '\"' + config_path + '\\' +
          time_str1 + '.log' + '\"')
    print('\n')
finally:
    print('Press any key to quit program.')
    ord(msvcrt.getch())

02

# File: py_net_config.py
# Time: 2022/05/13 12:19:59
# Author: Kir
# Ver: 2.0
# Description:AutoConfig/SSH/Log

import time
from netmiko import ConnectHandler, NetMikoAuthenticationException, NetMikoTimeoutException
import os
import re
import msvcrt
import getpass

try:
    # 校验账户交给netmiko模块,仅输入
    login_user = input('Login:')
    login_pwd = getpass.getpass('Passwd:')
    # 时间格式蒸鹅心,冒号不能用做文件名字符
    time_str1 = time.strftime('%Y%m%d', time.localtime())
    time_str2 = time.strftime('%H%M%S', time.localtime())
    time_str3 = time.strftime('%H:%M:%S', time.localtime())
    # 获取当前工作目录
    path = os.getcwd()
    title = "%s" % time_str1
    # mkdir path & touch file
    new_path = os.path.join(path, title)
    config_path = "%s\\configure_device" % new_path
    if not os.path.isdir(new_path):
        os.makedirs(new_path)
    if not os.path.isdir(config_path):
        os.makedirs(config_path)
    # 创建日志文件,记录运行结果
    log_fo = open(
        '%s\\%s.log' % (config_path, time_str1),
        'a+',
        encoding='utf-8',
    )
    log_fo.write('\n' + "==========START TIME " + time_str3 + "=========" +
                 '\n')
    # 读取 ip_list.txt 里的 ip 地址
    ip_list = open('ip_list.txt', 'r', encoding='ascii')
    ip_addr = ip_list.readlines()
    ip_list.close()
    # 读取 cmd_config_list.txt 文件的配置命令
    cmd_config_list = open('cmd_config_list.txt', 'r', encoding='ascii')
    cmd_line = cmd_config_list.readlines()
    print('AddCommand-line: ' + str(cmd_line))
    cmd_config_list.close()

    # 遍历 ip_addr 列表里面的 ip 进行连接
    for ip in iter(ip_addr):
        try:
            S5130 = {
                'device_type': 'hp_comware',
                'ip': ip,
                'username': login_user,
                'password': login_pwd,
            }

            net_connect = ConnectHandler(**S5130)
            # 禁用输出屏幕分屏
            screen_d = net_connect.send_command('screen-length disable')
            # current_time as part of filename
            time_str2 = time.strftime('%H%M%S', time.localtime())
            # sysname as part of fielname
            sysn = net_connect.send_command('dis cur | inc sysname')
            # split 空格分割回显内容
            sysn = re.split(r'[ ]+', sysn)
            sysn = sysn[2]
            # 创建文件, 格式为 sysname + time_str2
            config_fo = open('%s\\%s_%s_add_config.txt' %
                             (config_path, sysn, time_str2),
                             'a',
                             encoding='utf-8')
            time_str3 = time.strftime('%H:%M:%S', time.localtime())
            print(time_str1 + "_" + time_str3 + ' Successfully connected to ' +
                  ip + ' Configuring...')
            log_fo.write(time_str1 + "_" + time_str3 +
                         ' Configuration complete: ' +
                         ' Successfully connected to ' + ip)
            # 发送 cmd_line
            cmd_result = net_connect.send_config_set(cmd_line)
            print(cmd_result)
            print(
                '==================================================================='
            )
            config_fo.write(
                '\n' +
                '==================================================================='
                + '\n' + cmd_result)
            net_connect.disconnect()
            config_fo.close()
        except (EOFError, NetMikoTimeoutException):
            print('Can not connect to Device ' + ip)
            time_str3 = time.strftime('%H:%M:%S', time.localtime())
            log_fo.write(time_str1 + "_" + time_str3 +
                         ' Configuration Fail: ' +
                         ' Can not connect to Device! ' + ip)
        except (EOFError, NetMikoAuthenticationException):
            print('username/password wrong! ' + ip)
            time_str3 = time.strftime('%H:%M:%S', time.localtime())
            log_fo.write(time_str1 + "_" + time_str3 +
                         ' Configuration Fail: ' +
                         ' username/password wrong! ' + ip)
    time_str4 = time.strftime('%H:%M:%S', time.localtime())
    log_fo.write('\n' + "==========END TIME " + time_str4 + "==========" +
                 '\n')
    log_fo.close()
    print('\n')
    print('A log file is available in ' + '\"' + config_path + '\\' +
          time_str1 + '.log' + '\"')
    print('\n')
finally:
    print('Press any key to quit program.')
    ord(msvcrt.getch())

参考资料:

- Python-交换机自动化巡检脚本笔记 by 02EVA on 2021-04-22 : https://blog.csdn.net/weixin_42065669/article/details/116009445
-「Python 网络自动化」Netmiko ——Netmiko 常用方法 by 某呆啊 on 2021-02-04 : https://blog.csdn.net/q965844841qq/article/details/113619281
- Python 逐行读取txt 文件并生成列表 by 诺亚方包 on 2020-05-19 : https://blog.csdn.net/weixin_40973138/article/details/106209020
- Python 使用 Netmiko 连接 H3C 网络设备 by 某呆 on 2021-02-03  : https://555.xdai.vip/posts/26e9de3c.html
- H3C交换机python命令下发脚本 by xuwenfang1989 on 2018-08-27 : https://blog.51cto.com/u_1339643/2164819
- Python实现“按任意键返回”和无回显输入 by dongfuguo on 2020-03-25 : https://blog.csdn.net/dongfuguo/article/details/105103446
- Python3文件路径/目录获取教程 by 诸子流 on 2020-07-09 : `https://www.cnblogs.com/lsdb/p/13265688.html
- 如何让python不打印转义字符串?by 流芳 on 2020-07-07 : https://www.py.cn/jishu/jichu/19480.html