CentOS Python自動化運維可以通過多種方式實現,主要包括連接遠程服務器、文件傳輸、監控與報警、定時任務執行等。以下是具體的實現方法:
使用Python的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文件傳輸協議,支持快速上傳和下載文件。
import paramiko
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('hostname', port=22, username='your_username', password='your_password')
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
庫可以實時監控服務器的CPU、內存等信息,并通過郵件或其他方式報警。
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'
server = smtplib.SMTP('smtp.example.com')
server.login('user', 'password')
server.sendmail('your_email@example.com', ['alert_recipient@example.com'], msg.as_string())
server.quit()
在CentOS中,可以使用crontab
來管理定時任務。通過crontab -e
命令編輯當前用戶的定時任務列表。
*/1 * * * * /usr/bin/python3 /path/to/your/script.py
這條命令表示每小時執行一次/path/to/your/script.py
腳本。
使用PyInstaller
可以將Python腳本打包成可執行文件,便于部署到其他Linux系統上。
pip3 install pyinstaller
pyinstaller --onefile your_script.py
生成的可執行文件將位于dist
目錄下,可以復制到其他系統上直接運行。
可以創建一系列的Shell腳本來自動化環境初始化、安裝依賴、配置防火墻等任務。
#!/bin/bash
# install_dependencies.sh
yum install -y python3 python3-pip
pip3 install virtualenv
通過這些步驟,你可以在CentOS上實現Python自動化運維,提高工作效率并減少人為錯誤。