要使用Python检索远程主机的TLS/SSL对等证书,您可以使用ssl
库和socket
库。以下是一个示例代码:
import socket
import ssl
def get_remote_certificate(hostname, port):
context = ssl.create_default_context()
with socket.create_connection((hostname, port)) as sock:
with context.wrap_socket(sock, server_hostname=hostname) as ssock:
certificate = ssock.getpeercert()
return certificate
hostname = 'example.com'
port = 443
certificate = get_remote_certificate(hostname, port)
print(certificate)
在这个示例中,我们首先导入socket
和ssl
库。然后,我们定义一个名为get_remote_certificate
的函数,该函数接受主机名和端口号作为参数。在函数内部,我们创建一个默认的SSL上下文,并使用create_connection
函数创建一个TCP连接。接下来,我们使用wrap_socket
函数将TCP连接升级为SSL连接,并传递主机名以进行服务器名称指示(SNI)。最后,我们使用getpeercert
函数获取对等证书,并返回它。
在主程序中,我们定义一个主机名和端口号,然后调用get_remote_certificate
函数以获取对等证书。最后,我们打印证书信息。
请注意,这个示例仅适用于支持SNI的服务器。如果您需要检索不支持SNI的服务器的证书,您需要使用其他方法。
领取专属 10元无门槛券
手把手带您无忧上云