华为设备自动化脚本优化建议

本文将针对提供的代码片段进行优化建议,以提高脚本的代码规范性、可维护性、效率和健壮性。

1. 代码规范

  • 变量命名: 使用更具描述性的变量名,例如 device_ip 而不是 ipusername 而不是 usr
  • 代码格式: 使用统一的代码风格,例如使用四个空格缩进,空行使用适当的间隔,增加代码的可读性。
  • 模块导入: 使用 import ... as ... 形式简化模块导入语句。
  • 错误处理: 使用 try...except 块处理可能出现的异常,提高代码健壮性。

2. 可维护性

  • 硬编码: 将硬编码的信息,例如设备 IP 地址、用户名和密码,抽离出来,放到配置文件或者命令行参数中,增强代码的可配置性和可维护性。
  • 函数封装: 将重复的代码封装成函数,提高代码复用性和可读性。

3. 效率

  • 资源管理: 使用 with 语句自动管理资源,避免手动关闭连接。
  • 并发性能: 使用多线程或者协程技术提高程序的并发性能,加快数据处理速度。
  • 非阻塞IO: 在发送命令和接收命令输出时,使用非阻塞IO技术,增加程序的响应速度和吞吐量。
  • 批量命令: 在运行命令时,使用批量命令的方式,减少网络传输的次数,提高程序的执行效率。

4. 健壮性

  • 断点续传: 在下载配置文件时,使用断点续传的方式,避免网络中断或者程序异常导致下载失败,提高程序的健壮性。
  • 备份和版本控制: 在保存配置文件时,使用备份和版本控制的方式,避免误操作或者数据丢失,增强程序的可靠性和安全性。
  • 日志记录和告警: 在异常处理时,使用日志记录和告警提示的方式,及时发现问题并解决,防止问题扩大化。

代码示例

# 导入所需模块
from paramiko import SSHClient, AutoAddPolicy
from time import sleep, localtime, strftime, time
from ncclient import manager

# 配置信息
class Config:
    def __init__(self):
        self.device_ip = '10.1.0.6'
        self.ssh_username = 'sshuser'
        self.ssh_password = 'Huawei@123'
        self.nc_username = 'netconf'
        self.nc_password = 'Huawei@123'
        self.command_file = 'command.txt'
        self.backup_filename = strftime('%Y_%m_%d', localtime(time())) + '_X_T1_AGG1_vrpcfg.zip'
        self.syslog_conf = '''
<config>
      <syslog:syslog xmlns:syslog='urn:ietf:params:xml:ns:yang:ietf-syslog'>
        <syslog:log-actions>
          <syslog:remote>
            <syslog:destination>
              <syslog:name>log-center server</syslog:name>
              <syslog:udp>
                <syslog:address xmlns:xc='urn:ietf:params:xml:ns:netconf:base:1.0' xc:operation='merge'>10.1.60.2</syslog:address>
              </syslog:udp>
            </syslog:destination>
          </syslog:remote>
        </syslog:log-actions>
      </syslog:syslog>
    </config>
'''

# 定义 HCIE 类
class HCIE:
    def __init__(self, config):
        self.config = config
        self.client = self._get_connect()
        self.cli = self.client.invoke_shell()
        self.cli.send('n\n')
        self.cli.send('screen-length 0 temporary\n')
        self.cli.recv(65535)

    # 连接设备
    def _get_connect(self):
        ssh_con = SSHClient()
        ssh_con.set_missing_host_key_policy(AutoAddPolicy)
        ssh_con.connect(hostname=self.config.device_ip, username=self.config.ssh_username, password=self.config.ssh_password)
        return ssh_con

    # 运行命令
    def cmd_running(self):
        with self._get_connect() as ssh_con:
            with open(self.config.command_file, 'r') as f:
                cmd_list = f.readlines()
                for cmd in cmd_list:
                    self.cli.send(cmd)
                    sleep(1)
                    dis_this = self.cli.recv(65535).decode()
                    if cmd == 'display fan\n':
                        state = dis_this.find('Normal')
                        if state < 0:
                            print('All fans are faulty')
                    print(dis_this)

    # 保存配置
    def save_running(self):
        with self._get_connect() as ssh_con:
            cmd = 'save ' + self.config.backup_filename
            self.cli.send('{}
'.format(cmd))
            self.cli.send('y\n')
            self.cli.send('y\n')
            sleep(1)
            dis_this = self.cli.recv(65535).decode()
            print(dis_this)

    # 下载配置文件
    def download_file(self):
        with self._get_connect() as ssh_con:
            with ssh_con.open_sftp() as sftp_con:
                l_path = self.config.backup_filename
                r_path = '/' + l_path
                sftp_con.get(localpath=l_path, remotepath=r_path)
                sleep(1)

    # 进入netconf模式
    def netconf(self):
        with self._get_connect() as ssh_con:
            self.cli.send('sys\n')
            self.cli.send('netconf\n')
            self.cli.send('y\n')
            self.cli.send('source ip 10.1.0.6 port 830\n')
            sleep(10)
            dis_this = self.cli.recv(65535).decode()
            print(dis_this)

    # 关闭连接
    def close(self):
        self.client.close()

# 编辑syslog服务器地址
def edit_loghost(config):
    with manager.connect_ssh(
        host=config.device_ip,
        username=config.nc_username,
        password=config.nc_password,
        hostkey_verify=False,
        device_params={'name': 'huaweiyang'}
    ) as m:
        m.edit_config(config=config.syslog_conf, target='running')
        sleep(1)

# 数据循环处理
def datacom_loop(config):
    now_time = time()
    while True:
        datacom = HCIE(config)
        datacom.cmd_running()
        last_time = time()
        if last_time - now_time >= 86400:
            datacom.save_running()
            datacom.download_file()
            now_time = time()
        elif last_time - now_time < 300:
            datacom.save_running()
            datacom.download_file()
        datacom.close()
        sleep(300)

# 进入netconf模式
def netconf(config):
    netconf = HCIE(config)
    netconf.netconf()
    netconf.close()

if __name__ == '__main__':
    try:
        config = Config()
        netconf(config)
        edit_loghost(config)
        datacom_loop(config)
    except KeyboardInterrupt:
        print('Monitoring has stopped!')

上述代码示例只是针对代码规范性和可维护性进行了改进,实际的优化方案需要根据具体的需求进行调整。

注意: 代码示例仅供参考,实际应用中需要根据具体情况进行调整。

华为设备自动化脚本优化建议

原文地址: https://www.cveoy.top/t/topic/obaI 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录