天天看點

利用python對ssl證書資訊進行批量檢測-批量檢測ssl證書是否過期

主要使用到了Linux中的curl對證書資訊進行擷取,利用python通過正則截取資訊中需要的部分

【直接看下面代碼,python3.6  、centos7 測試通過】

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

import re
import subprocess
from optparse import OptionParser


def main(domain):

	cmd='curl -lvs https://{}/'.format(domain)
	sslinfo=subprocess.getstatusoutput(cmd)[1]

	print('domain:',domain)
	m=re.search('subject:(.*?)\n.*?start date:(.*?)\n.*?expire date:(.*?)\n.*?common name:(.*?)\n.*?issuer:(.*?)\n',sslinfo)
	print('subject:',m.group(1))
	print('start date:',m.group(2))
	print('expire date:',m.group(3))
	print('common name:',m.group(4))
	print('issuer:',m.group(5))
	print('*'*80)
	pass


if __name__ == '__main__':

	domains=[]
	parser=OptionParser()
	parser.set_usage('python sslinfoGather.py -d domain   \n  	python sslinfoGather.py -f fileName')
	parser.add_option('-d','--domain',dest='domainName',help=' put the domain name')
	parser.add_option('-f','--file',dest='fileName',help=' put the fileName which cotains domains;one line one domain')

	options,_=parser.parse_args()
	if(options.domainName==None and options.fileName==None):
		# parser.print_usage()
		parser.print_help()
		exit()
	if options.domainName!=None:
		domains.append(options.domainName)

	if options.fileName!=None:
		f=open(options.fileName)
		for domain in f:
			domains.append(domain)

	if len(domains)>0:
		# domains=['www.baidu.com','www.sina.cn','www.jd.com']
		for domain in domains:
			try:
				main(domain)
			except Exception as e:
				print('use python3 please\nError info:',str(e))
				exit()
			
	else:
		print('input wrong ,check again!!!')
           

測試結果1:從檔案中讀取域名資訊

利用python對ssl證書資訊進行批量檢測-批量檢測ssl證書是否過期

測試結果2:從指令行直接讀取域名資訊

利用python對ssl證書資訊進行批量檢測-批量檢測ssl證書是否過期

各位如果有需要,可以修改腳本根據證書的起止時間判斷證書是否即将過期