Parse WHOIS Data with Python Regex
Extract domain registration fields from a mock WHOIS record using regex and compute days until expiration.
Python code
39 linesimport re
from datetime import datetime
def parse_whois(whois_text: str) -> dict:
"""Extract key registration fields from a mock WHOIS record."""
patterns = {
"domain": r"Domain Name:\s*(.+)",
"registrar": r"Registrar:\s*(.+)",
"creation_date": r"Creation Date:\s*(.+)",
"expiry_date": r"Expiry Date:\s*(.+)",
"status": r"Status:\s*(.+)",
}
parsed = {}
for key, pattern in patterns.items():
match = re.search(pattern, whois_text, re.IGNORECASE)
if match:
parsed[key] = match.group(1).strip()
return parsed
def days_until_expiry(expiry_date_str: str) -> int:
"""Return days remaining until domain expiry."""
expiry = datetime.strptime(expiry_date_str, "%Y-%m-%d")
return (expiry - datetime.now()).days
if __name__ == "__main__":
mock_whois = """Domain Name: example.com
Registrar: Mock Registrar LLC
Creation Date: 2015-06-01
Expiry Date: 2025-06-01
Status: clientTransferProhibited"""
info = parse_whois(mock_whois)
print(f"Domain: {info['domain']}")
print(f"Registrar: {info['registrar']}")
print(f"Expires in: {days_until_expiry(info['expiry_date'])} days")
print(f"Status: {info['status']}")
Output
Domain: example.com
Registrar: Mock Registrar LLC
Expires in: 342 days
Status: clientTransferProhibited
How it works
The parse_whois function uses named regex patterns to capture key fields from the WHOIS text. The re.IGNORECASE flag makes matching case-insensitive. datetime.strptime converts the expiry date string into a datetime object for comparison with datetime.now(). The main block formats and prints the extracted information alongside the days remaining until expiration.
Common mistakes
- Forgetting to use `re.search` vs `re.match`, which anchors matching to the start
- Assuming date formats are consistent across all registrars
- Not stripping whitespace from matched groups, leading to unclean values
Variations
- Use `re.compile` to precompile patterns for repeated calls
- Parse WHOIS data with `whois` library for real domain lookups
Real-world use cases
- Automating domain portfolio monitoring to flag upcoming expirations for renewal.
- Building an internal tool that audits registrars and domain statuses across a company.
- Integrating WHOIS parsing into a script that validates domain ownership for certificate issuance.
Sponsored
More from Automation & scripting
- Aggregate Log Errors Count by Hour in Python easy
- Automate Tweeting New Blog Posts in Python easy
- Automatically Clean Temporary Files from Applications Using Python medium
- Automatically Download the Latest Software Release from GitHub with Python medium
- Automatically Generate Charts from CSV Files with One Command medium
- Automatically Generate Hardware Inventory Reports in Python easy
Keep learning
Related tutorials and quizzes for this topic.