近期发现有个别网站的证书到期后未及时更新导致的一系列问题,所以需要写个脚本监控一下
网站一搜发现都是需要你提前把证书弄下来的,有了证书,然后再去链接…..感觉有点麻烦(我就是懒)
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 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 |
#!/usr/bin/env python import urllib2 import httplib import ssl import socket import os CERT_FILE = os.path.join(os.path.dirname(__file__), 'cacert.pem') class ValidHTTPSConnection(httplib.HTTPConnection): "This class allows communication via SSL." default_port = httplib.HTTPS_PORT def __init__(self, *args, **kwargs): httplib.HTTPConnection.__init__(self, *args, **kwargs) def connect(self): "Connect to a host on a given (SSL) port." sock = socket.create_connection((self.host, self.port), self.timeout, self.source_address) if self._tunnel_host: self.sock = sock self._tunnel() self.sock = ssl.wrap_socket(sock, ca_certs=CERT_FILE, cert_reqs=ssl.CERT_REQUIRED) class ValidHTTPSHandler(urllib2.HTTPSHandler): def https_open(self, req): return self.do_open(ValidHTTPSConnection, req) opener = urllib2.build_opener(ValidHTTPSHandler) def test_access(url): print "Acessing", url page = opener.open(url) print page.info() data = page.read() print "First 100 bytes:", data[0:100] print "Done accesing", url print "" # This should work test_access("https://www.google.com") # Accessing a page with a self signed certificate should not work # At the time of writing, the following page uses a self signed certificate test_access("https://tidia.ita.br/") |
然后又找到一种不需要提前下载证书的:
1 2 3 4 5 |
import OpenSSL import ssl, socket cert=ssl.get_server_certificate(('www.google.com', 443)) x509 = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM, cert) x509.get_notAfter() |
记得提前安装pip install pyopenssl
Latest posts by Zhiming Zhang (see all)
- aws eks node 自动化扩展工具 Karpenter - 8月 10, 2022
- ReplicationController and ReplicaSet in Kubernetes - 12月 20, 2021
- public key fingerprint - 5月 27, 2021