在CentOS系统上进行Python自动化运维,可以按照以下步骤进行:
sudo yum install python3
curl -O https://bootstrap.pypa.io/get-pip.py python3 get-pip.py
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') output = stdout.read().decode() print(output) ssh.close()
paramiko
库进行文件的上传和下载:sftp = ssh.open_sftp() sftp.put('local_file.txt', '/remote/path/remote_file.txt') sftp.get('/remote/path/remote_file.txt', 'local_downloaded_file.txt') sftp.close() ssh.close()
psutil
库监控系统资源,并使用smtplib
库发送报警邮件:import psutil import smtplib from email.mime.text import MIMEText cpu_usage = psutil.cpu_percent(interval=1) memory_info = psutil.virtual_memory() memory_usage = memory_info.percent if cpu_usage > 80 or memory_usage > 80: msg = MIMEText(f"警告!CPU使用率: {cpu_usage}%,内存使用率: {memory_usage}%") msg['Subject'] = '服务器性能警告' msg['From'] = 'your_email@example.com' msg['To'] = 'alert_recipient@example.com' with smtplib.SMTP('smtp.example.com') as server: server.send_message(msg)
crontab -e
命令编辑定时任务,例如每分钟运行一次监控脚本:* * * * * /usr/bin/python3 /path/to/your_script.py
crontab -l
删除定时任务:crontab -r
重启cron服务:systemctl restart crond
pip3 install pyinstaller pyinstaller --onefile your_script.py
生成的可执行文件位于dist
目录下,可以复制到其他Linux系统上运行。对于更复杂的自动化运维需求,可以使用开源项目如Ansible或Fabric。
通过以上步骤,你可以在CentOS下使用Python进行自动化运维操作,包括远程连接、文件传输、系统监控与报警、定时任务配置以及应用的自动化部署。