Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
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):
return 1
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 (, 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:
elif len(sys.argv) == 3:
print(connect(sys.argv[1], ip=sys.argv[2]))
print("usage: python hostname ip (optional)")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment