1、項目背景
服務證書到期需要更新,但如果更新滞後,會導緻服務停用,是以需要監測證書的到期時間,提前幾天通知相關運維及時更新證書,廢話不說,直接上代碼
2、編寫腳本
本内容如下:
cat check-cert-expire.py
#!/usr/bin/env python3
# --*-- coding: utf-8 --*--
# Author: 明日人生
# Version: 1.0
# Attention: 通過域名獲驗證書的過期時間
import re
import subprocess
from datetime import datetime
import requests
import json
def get_re_match_result(pattern, string):
match = re.search(pattern, string)
return match.group(1)
def parse_time(date_str):
return datetime.strptime(date_str, "%m月 %d %H:%M:%S %Y GMT")
def format_time(date_time):
return datetime.strftime(date_time, "%Y-%m-%d %H:%M:%S")
def get_cert_info(domain):
"""獲驗證書資訊"""
cmd = f"curl -Ivs https://{domain} --connect-timeout 10"
exitcode, output = subprocess.getstatusoutput(cmd)
# 正則比對
start_date = get_re_match_result('start date: (.*)', output)
expire_date = get_re_match_result('expire date: (.*)', output)
# 解析比對結果
start_date = parse_time(start_date)
expire_date = parse_time(expire_date)
return {
'start_date': start_date,
'expire_date': expire_date
}
def get_cert_expire_date(domain):
"""獲驗證書剩餘時間"""
info = get_cert_info(domain)
#print(info)
expire_date = info['expire_date']
# 剩餘天數
return (expire_date - datetime.now()).days
def msg(text):
json_text = {
"msgtype": "text",
"at": {
"atMobiles": [
"11111"
],
"isAtAll": False
},
"text": {
"content": text
}
}
print(requests.post(api_url, json.dumps(json_text), headers=headers).content)
if __name__ == "__main__":
domain = ['www.baidu.com','www.qq.com']
for i in domain:
expire_date = get_cert_expire_date(i)
#print("域名%s,過期時間還剩%d天" %(i,expire_date))
text = ('告警: 域名%s過期時間還剩%d天' %(i,expire_date))
token ="394d4cdcdfdfdfdfdfdsferedrererererere"
headers = {'Content-Type': 'application/json;charset=utf-8'}
api_url = "https://oapi.dingtalk.com/robot/send?access_token=%s" % token
msg(text)
3、執行
python3 check-cert-expire.py

如果您喜歡本文,就請動動您的發财手為本文點贊評論轉發,讓我們一起學習更多運維相關知識,最後請記得關注我。