#!/usr/bin/env python3
import subprocess
import os
import shutil
import smtplib
from email.mime.text import MIMEText
from datetime import datetime
# 配置部分
SERVERS = [
{"host": "192.168.1.1", "user": "user1", "password": "pass1"},
{"host": "192.168.1.2", "user": "user2", "password": "pass2"}
]
LOG_DIR = "/var/log/myapp"
BACKUP_DIR = "/var/backup"
EMAIL_SENDER = "sender@example.com"
EMAIL_RECEIVER = "receiver@example.com"
EMAIL_SMTP_SERVER = "smtp.example.com"
EMAIL_SMTP_PORT = 587
EMAIL_LOGIN = "login"
EMAIL_PASSWORD = "password"
# 监控服务器资源
def monitor_resources():
for server in SERVERS:
print(f"Monitoring {server['host']}")
# 示例:使用SSH执行命令检查CPU使用率
# 这里使用subprocess模块来执行SSH命令
result = subprocess.run(
["ssh", "{}@{}".format(server['user'], server['host']), "top -bn1 | grep Cpu"],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE
)
if result.returncode == 0:
print(f"CPU Usage on {server['host']}: {result.stdout.decode().strip()}")
# 收集日志
def collect_logs():
now = datetime.now().strftime("%Y%m%d%H%M%S")
log_archive = shutil.make_archive(f"{LOG_DIR}_{now}", 'zip', LOG_DIR)
print(f"Logs collected and archived as {log_archive}")
# 自动化部署
def deploy_app():
print("Starting deployment...")
# 这里可以放置部署逻辑,例如使用rsync同步文件等
# 示例:使用rsync同步当前目录到远程服务器
for server in SERVERS:
subprocess.run(
["rsync", "-avz", ".", f"{server['user']}@{server['host']}:/deployment/directory"],
check=True
)
print("Deployment completed.")
# 备份
def backup_data():
print("Starting backup...")
backup_time = datetime.now().strftime("%Y%m%d%H%M%S")
backup_path = os.path.join(BACKUP_DIR, f"backup_{backup_time}.tar.gz")
subprocess.run(
["tar", "czf", backup_path, BACKUP_DIR],
check=True
)
print(f"Backup completed. File saved as {backup_path}")
# 发送邮件通知
def send_email(subject, message):
msg = MIMEText(message, 'plain', 'utf-8')
msg['From'] = EMAIL_SENDER
msg['To'] = EMAIL_RECEIVER
msg['Subject'] = subject
server = smtplib.SMTP(EMAIL_SMTP_SERVER, EMAIL_SMTP_PORT)
server.starttls()
server.login(EMAIL_LOGIN, EMAIL_PASSWORD)
server.sendmail(EMAIL_SENDER, EMAIL_RECEIVER, msg.as_string())
server.quit()
# 主逻辑
def main():
try:
monitor_resources()
collect_logs()
deploy_app()
backup_data()
send_email("Automation Script Completed", "The automation script has completed successfully.")
except Exception as e:
send_email("Automation Script Error", str(e))
if __name__ == "__main__":
main()
#!/usr/bin/env python3
import subprocess
import os
import shutil
import smtplib
from email.mime.text import MIMEText
from datetime import datetime
# 配置部分
SERVERS = [
{"host": "192.168.1.1", "user": "user1", "password": "pass1"},
{"host": "192.168.1.2", "user": "user2", "password": "pass2"}
]
LOG_DIR = "/var/log/myapp"
BACKUP_DIR = "/var/backup"
EMAIL_SENDER = "sender@example.com"
EMAIL_RECEIVER = "receiver@example.com"
EMAIL_SMTP_SERVER = "smtp.example.com"
EMAIL_SMTP_PORT = 587
EMAIL_LOGIN = "login"
EMAIL_PASSWORD = "password"
# 监控服务器资源
def monitor_resources():
for server in SERVERS:
print(f"Monitoring {server['host']}")
# 示例:使用SSH执行命令检查CPU使用率
# 这里使用subprocess模块来执行SSH命令
result = subprocess.run(
["ssh", "{}@{}".format(server['user'], server['host']), "top -bn1 | grep Cpu"],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE
)
if result.returncode == 0:
print(f"CPU Usage on {server['host']}: {result.stdout.decode().strip()}")
# 收集日志
def collect_logs():
now = datetime.now().strftime("%Y%m%d%H%M%S")
log_archive = shutil.make_archive(f"{LOG_DIR}_{now}", 'zip', LOG_DIR)
print(f"Logs collected and archived as {log_archive}")
# 自动化部署
def deploy_app():
print("Starting deployment...")
# 这里可以放置部署逻辑,例如使用rsync同步文件等
# 示例:使用rsync同步当前目录到远程服务器
for server in SERVERS:
subprocess.run(
["rsync", "-avz", ".", f"{server['user']}@{server['host']}:/deployment/directory"],
check=True
)
print("Deployment completed.")
# 备份
def backup_data():
print("Starting backup...")
backup_time = datetime.now().strftime("%Y%m%d%H%M%S")
backup_path = os.path.join(BACKUP_DIR, f"backup_{backup_time}.tar.gz")
subprocess.run(
["tar", "czf", backup_path, BACKUP_DIR],
check=True
)
print(f"Backup completed. File saved as {backup_path}")
# 发送邮件通知
def send_email(subject, message):
msg = MIMEText(message, 'plain', 'utf-8')
msg['From'] = EMAIL_SENDER
msg['To'] = EMAIL_RECEIVER
msg['Subject'] = subject
server = smtplib.SMTP(EMAIL_SMTP_SERVER, EMAIL_SMTP_PORT)
server.starttls()
server.login(EMAIL_LOGIN, EMAIL_PASSWORD)
server.sendmail(EMAIL_SENDER, EMAIL_RECEIVER, msg.as_string())
server.quit()
# 主逻辑
def main():
try:
monitor_resources()
collect_logs()
deploy_app()
backup_data()
send_email("Automation Script Completed", "The automation script has completed successfully.")
except Exception as e:
send_email("Automation Script Error", str(e))
if __name__ == "__main__":
main()