自动化运维脚本

#!/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()

  • 3
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值