之前在Red Hat Enterprise Linux Server release 6.1 (Santiago) Linux系统上使用过Python发送邮件(https://blog.csdn.net/zhu6201976/article/details/85809239),迁移到CentOS7却不行了,同样的代码,很是郁闷。

经过数小时折腾,查了大量资料,换来的却是一次次失败,一个简单的功能,因无法深入,几近崩溃......

偶得一文,解决了该问题:https://blog.csdn.net/ithongchou/article/details/83578337

以下代码为CentOS7使用Python发送邮件兼简单监控爬虫文件是否停止运行,仅供参考。

# coding=utf8
import os
import re
import smtplib
from email.header import Header
from email.mime.text import MIMEText


def send_email():
    """Centos7系统使用Python发邮件"""
    mail_host = "smtp.qq.com"  # 设置服务器
    mail_user = "414566019@qq.com"  # 用户名
    mail_pass = "******"  # 使用自己的口令
    sender = '414566019@qq.com'
    receivers = ['414566019@qq.com']  # 接收邮件(可设置多个)
    message = MIMEText('预警:toutiao_spider文件未完全运行!', 'plain', 'utf-8')
    message['From'] = Header("120.79.220.109", 'utf-8')
    message['To'] = Header("测试", 'utf-8')
    subject = 'toutiao_spider预警'
    message['Subject'] = Header(subject, 'utf-8')
    try:
        smtpObj = smtplib.SMTP_SSL(timeout=10)
        smtpObj.connect(mail_host, 465)
        smtpObj.login(mail_user, mail_pass)
        smtpObj.sendmail(sender, receivers, message.as_string())
        print('发送成功')
    except smtplib.SMTPException:
        print('发送失败')


def main():
    # 应执行的爬虫文件列表
    should_run_list = ['baidu_article.py', 'dayu_article.py', 'douban_movie_2.py', 'douban_tv_2.py',
                       'fenghuang_article.py', 'get_toutiao_comment2.py', 'kandian_article.py', 'kuaibao_article.py',
                       'mogu_ip.py', 'sohu_article.py', 'tjg_spider_2.py', 'toutiao_article.py',
                       'toutiao_profile_spider.py', 'toutiao_video.py', 'wangyi_article.py']
    real_run_list = []  # 实际运行爬虫文件列表
    process_list = os.popen('ps -aux | grep python3').readlines()
    for process in process_list:
        match = re.match(r'.*python3 /data/wwwroot/toutiao/(.*py).*', process)
        if match:
            real_run_list.append(match.group(1))

    should_run_list.sort()
    real_run_list.sort()
    if should_run_list != real_run_list:
        send_email()


if __name__ == '__main__':
    main()

Logo

脑启社区是一个专注类脑智能领域的开发者社区。欢迎加入社区,共建类脑智能生态。社区为开发者提供了丰富的开源类脑工具软件、类脑算法模型及数据集、类脑知识库、类脑技术培训课程以及类脑应用案例等资源。

更多推荐