在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進行自動化運維操作,包括遠程連接、文件傳輸、系統監控與報警、定時任務配置以及應用的自動化部署。