Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
#!/usr/bin/python3
from urllib.request import Request, urlopen, ssl, socket
from urllib.error import URLError, HTTPError
import json
import re
import sys
def connect(domain, port=443, ip=None):
"""
Connects to server to identify TLS certificate meta.
Accepts domain and optional port number and returns json.
"""
if not isValidDomain(domain):
print("invalid domain")
return 1
if ip is not None:
if not isValidIP(ip):
print('invalid')
return 1
else:
ip = socket.gethostbyname(domain)
with socket.create_connection((ip, port)) as sock:
with ssl.create_default_context().wrap_socket(sock, server_hostname=domain) as ssock:
return json.dumps(ssock.getpeercert())
def isValidDomain(str):
regex = "^((?!-)[A-Za-z0-9-]{1,63}(?<!-)\\.)+[A-Za-z]{2,6}"
p = re.compile(regex)
if (str == None):
return False
return (re.search(p, str))
def isValidIP(str):
regex = ""
p = re.compile(regex)
return True
if __name__ == '__main__':
# TODO: add port check or proper cli interface
if len(sys.argv) == 2:
print(connect(sys.argv[1]))
elif len(sys.argv) == 3:
print(connect(sys.argv[1], ip=sys.argv[2]))
else:
print("usage: python sslcheck.py hostname ip (optional)")
sys.exit(1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment