Python自动化运维脚本优化建议

本文提供了一些关于Python自动化运维脚本的优化建议,旨在提高脚本的可靠性和效率。

代码结构优化:

  1. 将命令列表文件读取方式改为with open() as f的方式,可以自动关闭文件。

  2. 在运行命令方法中,不需要再次连接设备获取ssh_con对象,可以直接使用self.client对象。

  3. 在保存配置、下载配置、进入netconf模式、关闭连接等方法中,不需要再次连接设备获取ssh_con对象,可以直接使用self.client对象。

  4. 在数据循环处理方法中,可以使用while True:代替while条件语句,可以避免在函数外定义now_time变量。

异常处理优化:

  1. 将保存、下载配置以及关闭连接等方法放在一个try...finally...语句中,可以确保即使出现异常,也能正常关闭连接。

性能优化:

  1. 将time()函数的调用次数减少,可以提高程序的效率。

示例代码(优化后):

# *utf-* python3
# 导入所需模块
from paramiko import SSHClient, AutoAddPolicy     # SSH连接库
from time import sleep, localtime, strftime, time  # 时间相关库
from ncclient import manager                       # NETCONF连接库

# 设备信息
dev_ip = '10.1.0.6'    # 设备IP地址
ssh_usr = 'sshuser'    # SSH用户名
ssh_pwd = 'Huawei@123' # SSH密码
c_usr = 'netconf'     # NETCONF用户名
c_pwd = 'Huawei@123'  # NETCONF密码
Command= 'command.txt'
name_time = strftime('%Y_%m_%d', localtime(time())) + '_X_T1_AGG1_vrpcfg.zip'

# 配置信息
c_conf_syslog = '''
<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, ip, usr, pwd):
        self.hostname = ip            # 设备IP地址
        self.username = usr           # SSH用户名
        self.password = pwd           # SSH密码
        self.client = self._get_connect()    # SSH连接对象
        self.cli = self.client.invoke_shell()   # SSH交互式终端对象
        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连接对象
        ssh_con.set_missing_host_key_policy(AutoAddPolicy)   # 未知主机密钥的策略
        ssh_con.connect(hostname=self.hostname, username=self.username, password=self.password)   # 连接设备
        return ssh_con

    # 运行命令
    def cmd_running(self):
        with open(Command, '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')    # 判断是否存在'Normal'
                    if state < 0:
                        print('All fans are faulty')   # 如果不存在,输出所有风扇异常
                print(dis_this)    # 输出命令输出内容

    # 保存配置
    def save_running(self):
        cmd = 'save ' + name_time    # 构造保存配置命令
        self.cli.send('{}\n'.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):
        sftp_con = self.client.open_sftp()    # 创建SFTP连接对象
        l_path = name_time  # 本地保存路径
        r_path = '/' + l_path   # 远程保存路径
        sftp_con.get(localpath=l_path, remotepath=r_path)   # 下载远程文件到本地
        sleep(1)

    # 进入netconf模式
    def netconf(self):
        self.cli.send('sys\n')   # 进入系统视图
        self.cli.send('netconf\n')   # 进入NETCONF模式
        self.cli.send('y\n')   # 确认进入NETCONF模式
        self.cli.send('source ip 10.1.0.6 port 830\n')   # 设置NETCONF连接参数
        sleep(10)
        dis_this = self.cli.recv(65535).decode()   # 接收命令输出
        print(dis_this)   # 输出命令输出内容

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

# 编辑syslog服务器地址
def edit_loghost(ip, usr, pwd, conf):
    with manager.connect_ssh(
        host=ip,
        username=usr,
        password=pwd,
        hostkey_verify=False,
        device_params={'name': 'huaweiyang'}
    ) as m:
        m.edit_config(config=conf, target='running')   # 编辑配置
        sleep(1)

# 数据循环处理
def datacom_loop(ip, usr, pwd):
    now_time = time()   # 记录当前时间
    while True:
        datacom = HCIE(ip, usr, pwd)
        try:
            datacom.cmd_running()   # 运行命令
            last_time = time()   # 记录当前时间
            if last_time - now_time >= 86400:   # 如果时间间隔大于等于1天
                datacom.save_running()   # 保存配置
                datacom.download_file()   # 下载配置
                now_time = time()   # 记录当前时间
            elif last_time - now_time < 300:   # 如果时间间隔小于5分钟
                datacom.save_running()   # 保存配置
                datacom.download_file()   # 下载配置
        finally:
            datacom.close()   # 关闭SSH连接
        sleep(300)   # 休眠300秒

# 进入netconf模式
def netconf(ip, usr, pwd):
    netconf = HCIE(ip, usr, pwd)
    netconf.netconf()   # 进入NETCONF模式
    netconf.close()   # 关闭SSH连接

if __name__ == '__main__':
    try:
        netconf(dev_ip, ssh_usr, ssh_pwd)   # 进入NETCONF模式
        edit_loghost(dev_ip, nc_usr, nc_pwd, nc_conf_syslog)   # 编辑syslog服务器地址
        datacom_loop(dev_ip, ssh_usr, ssh_pwd)   # 数据循环处理
    except KeyboardInterrupt:
        print('Monitoring has stopped!')   # 监控停止提示内容

总结:

本文所提到的优化建议,能够有效地提高Python自动化运维脚本的可靠性和效率。在实际应用中,还可以根据具体情况进行进一步的优化,例如使用多线程或多进程技术来提高脚本的执行速度。

Python自动化运维脚本优化建议

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

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