#!/usr/local/bin/python3.5 import socket, ssl import json from datetime import datetime import time import argparse import sys def getCertification(): try: context = ssl.create_default_context() conn = context.wrap_socket(socket.socket(socket.AF_INET), server_hostname=HOST) conn.connect((HOST, PORT)) cert = conn.getpeercert() #print(cert) if not [x[1] for x in cert["subjectAltName"] if x[1] == HOST]: # Host not found return "" else: return cert except: exit("handshake failed",sys.exc_info()[0]) else: print(-99) def calculateDate(cert): try: startdate = datetime.strptime(cert["notBefore"] , "%b %d %H:%M:%S %Y %Z") expire_date = datetime.strptime(cert["notAfter"] , "%b %d %H:%M:%S %Y %Z") nowdate = datetime.now() start_in = nowdate - startdate expire_in = expire_date - nowdate return expire_in.days except: pass def main(): parser = argparse.ArgumentParser() parser.add_argument('host', help='specify an host to connect to') parser.add_argument('-p', '--port', help='specify a port to connect to', type=int, default=443) args = parser.parse_args() global HOST, PORT HOST = args.host PORT = args.port cert = getCertification() if cert == "": exit("Host not found in DNS names") else: print(calculateDate(cert)) if __name__ == "__main__": main()