跳至正文
  • 7 views
  • 2 min read

检查证书过期时间并提前3天发送邮件提醒

新浪微博 豆瓣 QQ 百度贴吧 QQ空间

#!/usr/bin/env python3
# _*_ encoding:utf-8 _*_

import time
import subprocess
import smtplib
import sys
import datetime
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.header import Header


def execute_cmd(cmd):
    p = subprocess.Popen(
        cmd,
        shell=True,
        stdin=subprocess.PIPE,
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE
    )
    stdout, stderr = p.communicate()
    if p.returncode != 0:
        return p.returncode, stderr
    return p.returncode, stdout, stderr


def chk_cert(chktime):
    cmd = """
    openssl x509 -in /root/.acme.sh/xxx.xxx.xxx/xxx.xxx.xxx.cer -noout -dates|awk -F '=' '/notAfter/ {print }'
    """
    cert_end_time = execute_cmd(cmd)[1].decode().replace('\r', '').replace('\n', '').split('=')[-1]
    end_Time = int(time.mktime(time.strptime(cert_end_time, '%b %d %H:%M:%S %Y %Z')))
    curr_Time = int(time.time())
    one_Day_time = 24 * 60 * 60
    three_Days_time = one_Day_time * 3

    if (end_Time - curr_Time) < three_Days_time:
        print('[INFO]:{0}:Certification files needs to update now.'.format(chktime))
        return True
    else:
        rest_days = int((end_Time - curr_Time) / one_Day_time)
        print('[INFO]:{0}:Certification files are still over {1} days.'.format(chktime, rest_days))
        return False


def sent_mail ():
    smtpserver = "smtp.qq.com"
    smtpport = 465
    from_name = 'xxx'
    from_mail = "[email protected]"
    to_mail = ["[email protected]"]
    password = "xxx"

    smtp = smtplib.SMTP_SSL(smtpserver, smtpport)
    subject = "Needs to update you SSL now"
    body = "hi, the ssl certification is about to expired, please go to update it now."
    msgtext = MIMEText(body, "plain", "utf-8")
    msg = MIMEMultipart()
    msg["Subject"] = Header(subject, "utf-8")
    msg["From"] = Header(from_name + " <" + from_mail + ">")
    msg["To"] = Header(",".join(to_mail), "utf-8")
    msg.attach(msgtext)
    try:
        smtp.login(from_mail, password)
        smtp.sendmail(from_mail, to_mail, msg.as_string())
    except smtplib.SMTPException as e:
        print(e)
    finally:
        smtp.quit()


def main():
    chktime = datetime.datetime.now().strftime('%Y/%m/%d-%H:%M')
    if chk_cert(chktime):
        sent_mail()
    sys.exit(0)


if __name__ == '__main__':
    main()

发表回复