Improve readability with logging and adding support for output

This commit is contained in:
Blallo 2018-07-27 00:33:06 +02:00
parent 2a09c111f7
commit 97351a1070

View file

@ -1,19 +1,26 @@
#!/usr/bin/env python3
import hashlib
import logging
import ssl
import socket
import types
import click
logging.basicConfig(level=logging.INFO,
format='[%(levelname)-4s] %(message)s',
datefmt='%Y-%m-%d %H:%M')
logger = logging.getLogger('certo')
def establish_conn(addr, port, starttls):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(1)
try:
if starttls:
print("Using STARTTLS")
logger.debug("Using STARTTLS")
logger.debug("Connecting to %s:%s" % (addr, port))
sock.connect((addr, port))
sock.send(b"STARTTLS\n")
sock.recv(1000)
@ -22,7 +29,7 @@ def establish_conn(addr, port, starttls):
wrapped_socket = ssl.wrap_socket(sock)
wrapped_socket.connect((addr, port))
yield wrapped_socket.getpeercert(True)
return wrapped_socket.getpeercert(True)
finally:
wrapped_socket.close()
@ -31,7 +38,7 @@ def establish_conn(addr, port, starttls):
def get_cert(addr, port, starttls):
cert = establish_conn(addr, port, starttls)
pem_cert = ssl.DER_cert_to_PEM_cert(cert)
print(pem_cert)
logger.debug("The certificate is:\n%s" % pem_cert)
return cert
@ -39,18 +46,27 @@ def compute_fingerprints(cert):
thumb_md5 = hashlib.md5(cert).hexdigest()
thumb_sha1 = hashlib.sha1(cert).hexdigest()
thumb_sha256 = hashlib.sha256(cert).hexdigest()
print("MD5: " + thumb_md5)
print("SHA1: " + thumb_sha1)
print("SHA256: " + thumb_sha256)
logger.info("MD5: " + thumb_md5)
logger.info("SHA1: " + thumb_sha1)
logger.info("SHA256: " + thumb_sha256)
@click.command()
@click.argument('address')#, help="address to be used to retrieve the certificate")
@click.option('-p', '--port', default=443, type=click.IntRange(1,65535), help="the port to connect to")
@click.option('--starttls', is_flag=True, flag_value=True, help="wether to use starttls on connection")
def doit(address, port, starttls):
@click.option('-p', '--port', default=443, type=click.IntRange(1,65535), help="The port to connect to.")
@click.option('--starttls', is_flag=True, flag_value=True, help="Whether to use starttls on connection.")
@click.option('--debug/--nodebug', is_flag=True, flag_value=False, help="Debug output.")
@click.option('-o', '--output', help="Path to save the certificate to.")
def doit(address, port, starttls, debug, output):
if debug:
logger.setLevel(logging.DEBUG)
cert = get_cert(address, port, starttls)
if output:
with open(output, 'w') as f:
logger.debug("Opening file %s" % output)
f.write(ssl.DER_cert_to_PEM_cert(cert))
logger.info("The certificate has been saved to %s" % output)
compute_fingerprints(cert)
if __name__ == '__main__':