在CentOS服务器环境中,定时执行Python邮件发送任务是系统监控、业务报表自动化等场景的核心需求。本文以CentOS 7/8系统为测试环境,结合Cron与Systemd两种主流定时方案,详细阐述从脚本开发到任务调度的完整实现流程,并针对安全、日志等关键环节提供优化方案。
Python通过
smtplib与
email库实现邮件功能,支持纯文本、HTML、附件等多种格式。以下是一个集成安全认证与日志记录的完整脚本示例:
python1#!/usr/bin/env python32# -*- coding: utf-8 -*-3import smtplib4from email.mime.text import MIMEText5from email.mime.multipart import MIMEMultipart6from datetime import datetime7import logging8import os910# <"www.gov.cn.huainan.manct.cn">日志配置11logging.basicConfig(12 filename='/var/log/email_sender.log',13 level=logging.INFO,14 format='%(asctime)s - %(levelname)s - %(message)s'15)1617# 邮件配置(建议通过环境变量或配置文件管理敏感信息)18SMTP_SERVER = os.getenv('SMTP_SERVER', 'smtp.office365.com')19SMTP_PORT = int(os.getenv('SMTP_PORT', 587))20SENDER_EMAIL = os.getenv('SENDER_EMAIL', 'your_email@example.com')21SENDER_PASSWORD = os.getenv('SENDER_PASSWORD', 'your_app_password') # 推荐使用应用专用密码2223def generate_report():24 """生成HTML格式业务报告"""25 report_data = f"""26 <h1>系统状态报告</h1>27 <p>生成时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}</p>28 <table border="1">29 <tr><th>指标</th><th>数值</th></tr>30 <tr><td>CPU使用率</td><td>75%</td></tr>31 <tr><td>内存剩余</td><td>2.4GB</td></tr>32 </table>33 """34 return report_data3536def send_email(subject, body, recipients):37 """发送邮件核心函数"""38 msg = MIMEMultipart()39 msg['From'] = SENDER_EMAIL40 msg['To'] = ', '.join(recipients)41 msg['Subject'] = subject42 msg.attach(MIMEText(body, 'html'))4344 try:45 with smtplib.SMTP(SMTP_SERVER, SMTP_PORT) as server:46 server.starttls()47 server.login(SENDER_EMAIL, SENDER_PASSWORD)48 server.sendmail(SENDER_EMAIL, recipients, msg.as_string())49 logging.info(f"邮件发送成功至: {recipients}")50 except Exception as e:51 logging.error(f"邮件发送失败: {str(e)}")5253if __name__ == "__main__":54 recipients = ['admin@example.com']55 email_subject = f"系统监控报告 - {datetime.now().strftime('%Y-%m-%d')}"56 email_body = generate_report()57 send_email(email_subject, email_body, recipients)
关键优化点:
logging<"www.gov.cn.bengbu.manct.cn">模块记录发送状态,便于故障排查。Cron是Linux系统级定时任务工具,适合简单、固定的调度需求。
bash1chmod +x /opt/scripts/email_report.py # 赋予可执行权限2chown root:root /opt/scripts/email_report.py # 修改所有者(可选)
bash1crontab -e # 进入编辑模式
添加以下行实现每天凌晨2:30执行:
bash130 2 * * * /usr/bin/python3 /opt/scripts/email_report.py >> /var/log/email_cron.log 2>&1
参数说明:
30 2 * * *:分钟、小时、日、月、周(每天2:30执行)。>> /var/log/email_cron.log 2>&1<"www.gov.cn.maanshan.manct.cn">:将标准输出和错误输出重定向至日志文件。bash1systemctl status crond # 检查Cron服务状态2tail -f /var/log/cron # 实时查看Cron执行日志
Systemd定时器提供更灵活的调度能力,适合需要依赖服务或复杂时间规则的场景。
ini1# /etc/systemd/system/email_report.service2[Unit]3Description=System Monitoring Email Report45[Service]6Type=simple7ExecStart=/usr/bin/python3 /opt/scripts/email_report.py8User=root # 指定执行用户
ini1# /etc/systemd/system/email_report.<"www.gov.cn.anqing.manct.cn">timer2[Unit]3Description=Run Email Report Daily45[Timer]6OnCalendar=*-*-* 02:30:00 # 每天2:30执行7Persistent=true # 若错过执行时间,下次启动时补执行89[Install]10WantedBy=timers.target
bash1systemctl daemon-reload2systemctl enable email_report.timer3systemctl start email_report.timer
bash1systemctl list-timers --all # 查看所有定时器2journalctl -u email_report.service # 查看服务执行日志
bash130 2 * * * <"www.gov.cn.quanzhou.manct.cn">export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin && /usr/bin/python3 /opt/scripts/email_report.py
psutil库获取CPU、内存数据,触发阈值时发送告警邮件。tail -n 100 /var/log/messages提取最新日志,附加至邮件。通过Cron与Systemd双方案,开发者可根据场景需求灵活选择定时任务工具。Python脚本的模块化设计(如分离配置、日志、邮件生成逻辑)进一步提升了系统的可维护性。在实际部署中,建议结合监控工具(如Prometheus+Alertmanager)实现更智能的邮件通知策略。
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/19545/viewspace-3100239/ ,如需转载,请注明出处,否则将追究法律责任。