Python獲取網站證書有效期
由於某些原因,需要驗證網站證書有效期,從而做出響應的措施來避免一些特殊情況的出現。
python:OpenSSL和ssl
首先考慮使用OpenSSL模塊和ssl模塊來完成需求,使用OpenSSL之前需要先安裝模塊-pyOpenSSL。
pip install pyopenssl
import OpenSSL
import ssl
def check_cert_valid():
# 這裏還有一些代碼,用來獲取域名列表,情況不同,不闡述了
for domain in domain_list: # 這裏是一些域名的列表,可以使用其他方式
# 這裏我直接使用了下述方法來獲取證書,並沒有將證書寫入文件
cert = ssl.get_server_certification((domain, 443)) # 一般是443端口,並且這裏默認返回
# 的是PEM證書
# 如果有cert文件的話,直接執行這裏
# cert_file_path = '' # cert證書文件路徑
# cert = open(cert_file_path).read() # 當然這裏也可以使用with來進行上下文管理
certification = OpenSSL.crypto.load_certification(OpenSSL.crypto.FILETYPE_PEN, cert)
valid_start_time = certification.get_notBefore() # 有效期起始時間
valid_end_time = certification.get_notAfter() # 有效期結束時間
pass # 接下來執行各自的操作即可
if __name__ == '__main':
check_cert_valid()
python+shell:subprocess和curl
在使用上述方法的時候,大部分域名都是正常的,但是部分域名的有效期不匹配,不清楚原因爲何,如果有大佬知道原因,煩請不吝賜教,感謝,之後又嘗試了這種方案。
首先需要安裝subprocess模塊
pip install subprocess
import subprocess
def check_cert_valid():
# 這裏還有一些代碼,用來獲取域名列表,情況不同,不闡述了
for domain in domain_list: # 這裏是一些域名的列表,可以使用其他方式
# curl命令,-k代表不使用認證到達ssl站點,-v顯示詳情,-s代表靜默,-o代表輸出
curl_cmd = "curl https://%s -k -v -s -o /dev/null" % domain[0]
return_code, output = subprocess.getstatusoutput(domain_str)
output_groups = re.search(
'SSL connection using (.*?)\n.*?start date: (.*?)\n.*?expire date: (.*?)\n.*?issuer: (.*?)\n.*?',
output, re.S)
if output_groups:
# 接下來的時間是字符串,可能不符合各位的預期,使用時間格式化來回處理一下即可
start_date = output_groups.groups()[1] # 有效期起始時間
expire_date = output_groups.groups()[2] # 有效期結束時間
pass
pass # 接下來執行各自的操作即可
if __name__ == '__main':
check_cert_valid()
但是在這裏操作的時候,遇見了亂碼的問題,也就是WWW-Authenticate: Basic realm="*******"
,這裏出現了亂碼,使用grep -v
命令也失敗,只能退出求其次,將內容先寫入文件,之後再重新讀文件,這裏走了彎路了,大佬有解決方法的話也忘不吝賜教,感謝,下面跳出來後來的命令。
curl_cmd = "curl https://%s -k -v -s -o /dev/null 2>/tmp/cert.txt;" \
"cat /tmp/cert.txt| grep -v 'WWW-Authenticate'" % domain[0]