HTTPS域名证书有效期校验

HTTPS域名证书有效期校验

  • OS:centos6
  • python:2.7.9+

centos6安装python3.6.4


yum install zlib-devel bzip2-devel openssl-devel ncurses-devel sqlite-devel readline-devel tk-devel gcc make
wget http://mirrors.sohu.com/python/3.6.4/Python-3.6.4.tgz
tar xf Python-3.6.4.tgz -C /usr/local/src/
cd /usr/local/src/Python-3.6.4
./configure --prefix=/usr/local/python
make -j 4
make install
ln -s /usr/local/python/bin/python3 /usr/local/bin/python

功能完整代码:

[root@instance-1 ~]# cat domain_ssl_check.py 
#!/usr/local/bin/python
#coding=utf-8
import socket
import ssl
import datetime
import sys

def ssl_expiry_datetime(domain_name):
    """获取域名的证书到期时间"""
    ssl_date_fmt = r'%b %d %H:%M:%S %Y %Z'
    context = ssl.create_default_context()
    conn = context.wrap_socket(
        socket.socket(socket.AF_INET),
        server_hostname=domain_name,
    )
    conn.settimeout(3.0)
    conn.connect((domain_name, 443))
    ssl_info = conn.getpeercert()
    return datetime.datetime.strptime(ssl_info['notAfter'], ssl_date_fmt)
	
def ssl_valid_time_remaining(domain_name):
    """获取证书到期剩下的天数"""
    expires = ssl_expiry_datetime(domain_name)
    return expires - datetime.datetime.utcnow()
	
def ssl_expires_in(domain_name):
    """检测域名的时间是否过期"""
    remaining = ssl_valid_time_remaining(domain_name)
    if remaining < datetime.timedelta(days=0):
        return 1
    elif remaining < datetime.timedelta(days=7):
        return 2
    else:
        return 3

domainName = sys.argv[1]
result = ssl_expires_in(domainName)
print(domainName,result)

测试:

[root@instance-1 ~]# cat d.txt
m.1xt007.com
www.ds3jmf.net

#!/bin/bash
cat d.txt |while read line
do
/root/domain_ssl_check.py $line 2>/dev/null || echo "$line 无法访问"
done