最近在写脚本的时候遇到个问题,当我想获得https网站的一些证书信息的时候通过浏览器可以看到,然后我想通过脚本批量获得网站证书信息的时候发现不知道怎么获取。一开始我是朝着爬虫的方向思考,然后网上查了不少类似关键词的文章,发现都是介绍爬虫爬取https网站报错,怎么解决ssl验证的问题,并不是获得网站的ssl相关信息。于是乎·········

python获取证书信息正文

环境准备:

python3.8(其他3以上的版本也是可以的,我用的是3.8)

ssl库

OpenSSL库(pip install pyopenssl进行安装)

具体代码实现:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
import ssl
import OpenSSL


def _get_cert_from_endpoint(server, port=443):
try:
cert = ssl.get_server_certificate((server, port))
except Exception:
return None
if not cert:
return None
# print(cert)
result = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM, cert)
subject = result.get_subject()
issued_to = subject.CN
issuer = result.get_issuer()
issued_by = issuer.CN
# print(issued_to, ":::::::", issued_by)
# return issued_to,issued_by
return {"cert":cert,"subject":subject,"issuer":issuer,"issued_to":issued_to,"issued_by":issued_by}


if __name__ == '__main__':
hostname_ip = "www.gcoperation.top"
port = '443'
issuedDic = _get_cert_from_endpoint(hostname_ip,port)
if issuedDic == None:
print("未找到ssl信息")
else:
print(issuedDic['cert'])
print(issuedDic['subject'])
print(issuedDic['issuer'])
print(issuedDic['issued_to'])
print(issuedDic['issued_by'])