centos

CentOS中如何利用Python进行自动化运维

小樊
42
2025-06-12 14:56:43
栏目: 编程语言

在CentOS中利用Python进行自动化运维可以通过多种工具和库来实现,以下是一些常见的方法和步骤:

  1. 系统监控与报警

    • 使用 psutil 库可以轻松获取系统的CPU、内存、磁盘和网络信息,并实现监控和报警功能。例如,监控CPU和内存使用率,并在超过阈值时发送邮件通知:
      import psutil
      import smtplib
      from email.mime.text import MIMEText
      
      def send_email(subject, message):
          sender = 'your_email@example.com'
          receivers = ['receiver_email@example.com']
          msg = MIMEText(message)
          msg['Subject'] = subject
          msg['From'] = sender
          msg['To'] = ', '.join(receivers)
          server = smtplib.SMTP('smtp.example.com')
          server.sendmail(sender, receivers, msg.as_string())
          server.quit()
      
      def monitor_system(interval):
          while True:
              cpu_usage = psutil.cpu_percent(interval=1)
              memory_info = psutil.virtual_memory()
              if cpu_usage > 80 or memory_info.percent > 80:
                  send_email('System Alert', f'CPU Usage: {cpu_usage}%, Memory Usage: {memory_info.percent}%')
              time.sleep(interval)
      
      if __name__ == "__main__":
          monitor_system(60)
      
  2. 定时任务执行

    • 使用 crontab 进行定时任务处理。例如,每分钟检查一次系统日志:
      * * * * * /usr/bin/python3 /path/to/your_script.py
      
  3. 自动化部署

    • 使用 Fabric 进行应用程序的自动化部署。例如,上传代码并重启服务:
      from fabric import Connection
      
      def deploy():
          conn = Connection('user@remote_server')
          conn.run('git pull')
          conn.run('pip install -r requirements.txt')
          conn.run('systemctl restart myapp')
          conn.put('monitor.py', '/var/www/myapp/')
          conn.run('nohup python /var/www/myapp/monitor.py &')
      
      if __name__ == "__main__":
          deploy()
      
  4. 文件操作

    • 使用 osshutil 模块进行文件的自动化操作,如批量重命名文件和自动备份文件:
      import os
      import shutil
      
      def bulk_rename(folder_path, old_name_part, new_name_part):
          for filename in os.listdir(folder_path):
              if old_name_part in filename:
                  new_filename = filename.replace(old_name_part, new_name_part)
                  os.rename(os.path.join(folder_path, filename), os.path.join(folder_path, new_filename))
                  print(f"renamed {filename} to {new_filename}")
      
      def backup_files(src_dir, dest_dir):
          if not os.path.exists(dest_dir):
              os.makedirs(dest_dir)
          for file in os.listdir(src_dir):
              full_file_name = os.path.join(src_dir, file)
              if os.path.isfile(full_file_name):
                  shutil.copy(full_file_name, dest_dir)
                  print(f"backed up {file} to {dest_dir}")
      
      source = '/path/to/source/directory'
      destination = '/path/to/destination/directory'
      backup_files(source, destination)
      
  5. 连接远程服务器

    • 使用 paramiko 库进行SSH连接,执行远程命令和文件传输:
      import paramiko
      
      ssh = paramiko.SSHClient()
      ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
      ssh.connect('hostname', port=22, username='your_username', password='your_password')
      stdin, stdout, stderr = ssh.exec_command('ls -l /tmp')
      output = stdout.read().decode()
      print(output)
      ssh.close()
      

通过这些方法和工具,可以在CentOS系统中利用Python实现自动化运维,提高工作效率和系统管理的可靠性。

0
看了该问题的人还看了