Skip to content

Instantly share code, notes, and snippets.

@abersheeran abersheeran/whois.py
Last active Aug 3, 2019

Embed
What would you like to do?
Get whois data
#!/usr/bin/python3
import os
import re
import socket
from functools import wraps
from mecache import File
import requests as req
file = File(os.path.join(os.path.dirname(os.path.abspath(__file__)), ".cache/whois.cache"))
def punycode(domain):
result = []
for _ in domain.split("."):
try:
_.encode("ascii")
result.append(_)
except UnicodeEncodeError:
result.append("xn--" + _.encode("punycode").decode("ascii"))
return ".".join(result)
@file.cache(30*24*60*60, lambda suffix: suffix)
def whois_server(suffix):
resp = req.get("https://www.iana.org/domains/root/db/"+suffix+".html", timeout=3)
return re.search("WHOIS Server:</b>\s*(?P<whois>.*)", resp.text).group("whois")
# @file.cache(24*60*60, lambda server, domain: f"{domain}")
def whois(server, domain):
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.connect((server, 43))
s.send(domain.encode("UTF-8")+b'\r\n')
result = bytearray()
while True:
data = s.recv(4096)
if not len(data):
break
result.extend(data)
s.close()
return bytes(result).decode('utf-8')
def parse(whois_data):
# TODO better parse
data = re.sub(">>>[\s\S]+", "", whois_data)
return data
if __name__ == "__main__":
import sys
try:
domain = punycode(sys.argv[1])
except IndexError:
print("must provide domain like: 'whois.py domain'")
sys.exit(1)
data = parse(whois(whois_server(domain.split(".")[-1]), domain))
print(data)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.