在CentOS下实现Python自动化运维可以通过多种方法和工具来完成,主要包括SSH远程连接、文件传输、系统监控与报警、定时任务执行等。以下是一个详细的指南,帮助你实现Python自动化运维在CentOS上的应用:
sudo yum install python3
sudo yum install python3-pip
pip3 install paramiko psutil smtplib fabric
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()
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()
import psutil
import smtplib
from email.mime.text import MIMEText
def send_email(subject, body, to_email):
from_email = "your_email@example.com"
password = "your_password"
smtp_server = "smtp.example.com"
msg = MIMEText(body)
msg['Subject'] = subject
msg['From'] = from_email
msg['To'] = to_email
with smtplib.SMTP(smtp_server, 587) as server:
server.starttls()
server.login(from_email, password)
server.sendmail(from_email, [to_email], msg.as_string())
cpu_usage = psutil.cpu_percent(interval=1)
if cpu_usage > 80:
send_email(subject="服务器告警:CPU使用率过高", body=f"当前CPU使用率为{cpu_usage}%,请尽快处理!", to_email="admin@example.com")
print("告警邮件已发送!")
使用crontab
来设置定时任务,使Python脚本定期运行。
crontab -e
添加定时任务,例如每分钟运行一次监控脚本:
* * * * * /usr/bin/python3 /path/to/your_script.py
使用Fabric
或Ansible
进行应用程序的自动化部署。
使用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()
使用Ansible进行配置管理:
编写YAML格式的Playbook来定义自动化任务,例如安装Nginx:
---
- name: Install Nginx
hosts: webservers
become: yes
tasks:
- name: Update apt cache
apt: update_cache
- name: Install Nginx
apt:
name: nginx
state: present
使用ansible-playbook
命令来执行:
ansible-playbook nginx.yml
通过以上步骤和工具,你可以在CentOS上实现一个功能全面的Python自动化运维系统,提高工作效率并减少人为错误。