Skip to content

Instantly share code, notes, and snippets.

@AberSheeran AberSheeran/whois.py
Last active Mar 13, 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
import requests as req
class Memory:
def __init__(self, path):
self.__path = path
self.load()
@property
def path(self):
return self.__path
def dump(self):
with open(self.__path, 'wb') as file:
pickle.dump(self.__pool, file)
def load(self):
if os.path.exists(self.__path):
with open(self.__path, "rb") as file:
self.__pool = pickle.load(file)
else:
self.__pool = {}
def get_cache(self, func, *args, **kwargs):
if self.__pool.get(func.__qualname__) is None:
self.__pool[func.__qualname__] = {}
return None
return self.__pool[func.__qualname__].get(pickle.dumps([args, kwargs]))
def set_cache(self, result, func, *args, **kwargs):
if self.__pool.get(func.__qualname__) is None:
self.__pool[func.__qualname__] = {}
self.__pool[func.__qualname__][pickle.dumps([args, kwargs])] = result
self.dump()
def cache(self, max_time):
def timeout(func):
@wraps(func)
def warpper(*args, **kwargs):
result = self.get_cache(func, *args, **kwargs)
if result is None or result["expired"] < time.time():
_result = func(*args, **kwargs)
self.set_cache({"value": _result, "expired": time.time() + max_time}, func, *args, **kwargs)
return _result
else:
return result['value']
return warpper
return timeout
memory = Memory(os.path.join(os.path.dirname(os.path.abspath(__file__)), "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)
@memory.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")
@memory.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')
@AberSheeran

This comment has been minimized.

Copy link
Owner Author

AberSheeran commented Mar 13, 2019

# use it in python just like this
domain = punycode(domain)
suffix = domain.split(".")[-1]
result = whois(whois_server(suffix), 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.