Python WhoisInfo Class: Programmatic Access to WHOIS Data
WHOIS is a query and response protocol widely used for querying databases that store the registered users or assignees of an Internet resource, such as a domain name, an IP address block, or an autonomous system. This Python class, WhoisInfo, provides a convenient and structured way to programmatically retrieve and parse WHOIS information for a given IP address by leveraging the system’s whois command-line utility.
Prerequisites
This class relies on the whois command-line utility being installed on the system where the Python script is executed.
On Debian/Ubuntu:
sudo apt install whoisOn Fedora/RHEL:
sudo dnf install whoisWhoisInfo Class Implementation
The WhoisInfo class encapsulates the logic for running the whois command, parsing its output, and extracting specific fields.
import subprocess
import re
import json
class WhoisInfo:
def __init__(self, ip_address):
"""
Initializes the WhoisInfo object with the target IP address.
"""
self.ip_address = ip_address
def _run_whois_command(self):
"""
Executes the 'whois' command for the stored IP address and captures its output.
Handles potential subprocess errors.
"""
try:
# Run the whois command in the terminal and capture the output
result = subprocess.run(
['whois', self.ip_address],
capture_output=True,
text=True,
check=True # Raise CalledProcessError for non-zero exit codes
)
return result.stdout
except subprocess.CalledProcessError as e:
# Handle errors if the whois command fails (e.g., host not found, network issues)
print(f"Error running whois command for {self.ip_address}: {e}")
return None
except FileNotFoundError:
print("Error: 'whois' command not found. Please install it (e.g., 'sudo apt install whois').")
return None
def _convert_to_json(self, whois_output):
"""
Converts the raw whois output into a dictionary (JSON-like structure).
Parses key-value pairs from the output.
"""
# Define a pattern for extracting key-value pairs (Key: Value)
# It handles multi-line values by only capturing up to the next key or end of string
key_value_pattern = re.compile(r'^\s*([^:]+?):\s*(.+?)(?=\n\s*\w+:\s*|\n*$)', re.MULTILINE | re.IGNORECASE)
data = {}
# Iterate over all matches found in the whois output
for match in key_value_pattern.finditer(whois_output):
key = match.group(1).strip()
value = match.group(2).strip()
# Handle potential duplicate keys by storing as list or overwriting
if key in data:
if isinstance(data[key], list):
data[key].append(value)
else:
data[key] = [data[key], value]
else:
data[key] = value
return data
def _extract_info(self, whois_output, field):
"""
Extracts a specific field's value from the whois output using a regex pattern.
"""
# Define a pattern for extracting a specific field (e.g., "Organization: Value")
field_pattern = re.compile(fr'^{re.escape(field)}:\s*(.+)\s*$', re.MULTILINE | re.IGNORECASE)
# Search for the pattern in the whois output
match = field_pattern.search(whois_output)
# If a match is found, return the captured value
if match:
return match.group(1).strip()
else:
return None
def get_all_info(self):
"""
Retrieves all available WHOIS information for the IP address and returns it as a JSON-like dictionary.
"""
whois_output = self._run_whois_command()
if whois_output:
whois_json = self._convert_to_json(whois_output)
return whois_json
else:
return None
def get_organization(self):
"""
Retrieves the 'Organization' field from the WHOIS information.
"""
whois_output = self._run_whois_command()
if whois_output:
organization = self._extract_info(whois_output, 'Organization')
return organization
else:
return None
def get_country(self):
"""
Retrieves the 'Country' field from the WHOIS information.
"""
whois_output = self._run_whois_command()
if whois_output:
country = self._extract_info(whois_output, 'Country')
return country
else:
return None
def get_specific_info(self, field):
"""
Retrieves a specific named field from the WHOIS information.
"""
whois_output = self._run_whois_command()
if whois_output:
info = self._extract_info(whois_output, field)
return info
else:
return None
# Example usage of the WhoisInfo class
if __name__ == "__main__":
target_ip_address = "8.8.8.8" # Replace with the desired IP address (e.g., "google.com", "203.0.113.45")
whois_info = WhoisInfo(target_ip_address)
print(f"--- WHOIS Information for {target_ip_address} ---")
# Method 1: Get all whois information in JSON format
all_info = whois_info.get_all_info()
if all_info:
print("\nAll Whois Information (JSON format):")
print(json.dumps(all_info, indent=2))
else:
print("\nCould not retrieve all WHOIS information.")
# Method 2: Get Organization
organization = whois_info.get_organization()
if organization:
print(f"\nOrganization: {organization}")
else:
print("\nOrganization: Not found or could not retrieve.")
# Method 3: Get Country
country = whois_info.get_country()
if country:
print(f"\nCountry: {country}")
else:
print("\nCountry: Not found or could not retrieve.")
# Method 4: Get specific information (e.g., 'Creation Date' or 'Registrant Name')
creation_date = whois_info.get_specific_info('Creation Date')
if creation_date:
print(f"\nCreation Date: {creation_date}")
else:
print("\nCreation Date: Not found or could not retrieve.")
registrant_name = whois_info.get_specific_info('Registrant Name')
if registrant_name:
print(f"\nRegistrant Name: {registrant_name}")
else:
print("\nRegistrant Name: Not found or could not retrieve.")