編寫運維自動化腳本的主要目標是提高工作效率、減少重復勞動并確保系統的穩定運行。以下是一個簡單的Python腳本示例,用于監控系統資源使用情況并在資源不足時發送警報。
import os
import time
import psutil
import smtplib
from email.mime.text import MIMEText
# 配置參數
monitor_interval = 60 # 監控間隔(秒)
email_sender = "your_email@example.com"
email_receiver = "recipient_email@example.com"
email_password = "your_email_password"
threshold = 80 # 資源使用閾值(百分比)
def send_email(subject, message):
msg = MIMEText(message)
msg['Subject'] = subject
msg['From'] = email_sender
msg['To'] = email_receiver
try:
with smtplib.SMTP_SSL("smtp.example.com", 465) as server:
server.login(email_sender, email_password)
server.sendmail(email_sender, email_receiver, msg.as_string())
except Exception as e:
print(f"發送郵件失敗: {e}")
def check_resource_usage():
cpu_usage = psutil.cpu_percent()
memory_usage = psutil.virtual_memory().percent
print(f"CPU 使用率: {cpu_usage}%")
print(f"內存使用率: {memory_usage}%")
if cpu_usage > threshold or memory_usage > threshold:
subject = "資源使用警報"
message = f"CPU 使用率: {cpu_usage}%, 內存使用率: {memory_usage}%。請檢查服務器資源。"
send_email(subject, message)
if __name__ == "__main__":
while True:
check_resource_usage()
time.sleep(monitor_interval)
這個腳本使用了psutil庫來獲取系統資源使用情況,并使用smtplib庫發送電子郵件警報。你需要根據實際情況修改配置參數、郵件服務器信息和閾值。
在編寫運維自動化腳本時,還需要考慮以下幾點:
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。