Skip to content

Instantly share code, notes, and snippets.

@abersheeran abersheeran/whois.py
Last active Apr 5, 2019

Embed
What would you like to do?
Get whois data
import os
import re
import socket
import pickle
import time
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)
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)
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')
if __name__ == "__main__":
import sys
try:
domain = punycode(sys.argv[1])
except IndexError:
print("must provide domain like: 'whois.py abersheeran.com'")
sys.exit(1)
print(whois(whois_server(domain.split(".")[-1]), domain))
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.