利用whois API 查询域名信息
手上的各种域名很多,有的备案了,不能轻易放弃,便决定写个Whois查询的程序,列举域名的过期时间,提前续费。
Python代码如下我使用的代码没有加账号密码的认证,有50次的限制
import urllib.request
import json
import xml.etree.ElementTree as etree
########################
# Fill in your details #
########################
domain = "google.com"
# A function to recursively print out multi-level dicts with indentation
def RecursivePrettyPrint(obj, indent):
for x in list(obj):
if isinstance(obj[x], dict):
print (' '*indent + str(x)[0:50] + ": ")
RecursivePrettyPrint(obj[x], indent + 5)
elif isinstance(obj[x], list):
print(' '*indent + str(x)[0:50] + ": " + str(list(obj[x])))
else:
print (' '*indent + str(x)[0:50] + ": " + str(obj[x])[0:50].replace("\n",""))
#######################
# Use a JSON resource #
#######################
format = "JSON"
url = 'http://www.whoisxmlapi.com/whoisserver/WhoisService?domainName=' + domain + '&username=' + username + '&password=' + password + '&outputFormat=' + format
# Get and build the JSON object
result = json.loads(urllib.request.urlopen(url).readall().decode('utf8'))
# Handle some odd JS cases for audit, whose properties are named '$' and '@class'. Dispose of '@class' and just make '$' the value for each property
if 'audit' in result:
if 'createdDate' in result['audit']:
if '$' in result['audit']['createdDate']:
result['audit']['createdDate'] = js['audit']['createdDate']['$']
if 'updatedDate' in result['audit']:
if '$' in result['audit']['updatedDate']:
result['audit']['updatedDate'] = js['audit']['updatedDate']['$']
# Get a few data members.
if ('WhoisRecord' in result):
registrantName = result['WhoisRecord']['registrant']['name']
domainName = result['WhoisRecord']['domainName']
createdDate = result['WhoisRecord']['createdDate']
# Print out a nice informative string
RecursivePrettyPrint(result, 0)
#######################
# Use an XML resource #
#######################
format = "XML"
url = 'http://www.whoisxmlapi.com/whoisserver/WhoisService?domainName=' + domain +'&outputFormat=' + format
result = etree.parse(urllib.request.urlopen(url))
root = result.getroot()
# A function to recursively build a dict out of an ElementTree
def etree_to_dict(t):
if (len(list(t)) == 0):
d = t.text
else:
d = {}
for node in list(t):
d[node.tag] = etree_to_dict(node)
if isinstance(d[node.tag], dict):
d[node.tag] = d[node.tag];
return d
# Create the dict with the above function.
result = {root.tag :etree_to_dict(root)}
# Get a few data members.
if ('WhoisRecord' in result):
registrantName = result['WhoisRecord']['registrant']['name']
domainName = result['WhoisRecord']['domainName']
createdDate = result['WhoisRecord']['createdDate']
# Print out a nice informative string
#print ("'" + registrantName + "' created " + domainName + " on " + createdDate)
RecursivePrettyPrint(result, 0)
PHP代码
<?php
//////////////////////////
// Fill in your details //
//////////////////////////
$domain = "google.com";
$format = "JSON"; //or XML
$url = 'http://www.whoisxmlapi.com/whoisserver/WhoisService?domainName='. $domain .'&outputFormat='. $format;
if($format=='JSON'){
/////////////////////////
// Use a JSON resource //
/////////////////////////
// Get and build the JSON object
$result = json_decode(file_get_contents($url));
// Print out a nice informative string
print ("<div>JSON:</div>" . RecursivePrettyPrint($result));
}
else{
////////////////////////
// Use a XML resource //
////////////////////////
$url = 'http://www.whoisxmlapi.com/whoisserver/WhoisService?domainName='. $domain .'&outputFormat='. $format;
// Get and build the XML associative array
$parser = new XMLtoArray();
$result = array("WhoisRecord" =>$parser->ParseXML($url));
// Print out a nice informative string
print ("<div>XML:</div>" . RecursivePrettyPrint($result));
}
// Function to recursively print all properties of an object and their values
function RecursivePrettyPrint($obj)
{
$str = "";
foreach ((array)$obj as $key => $value)
{
if (!is_string($key)) // XML parsing leaves a little to be desired as it fills our obj with key/values with just whitespace, ignore that whitespace at the cost of losing hostNames and ips in the final printed result
continue;
$str .= '<div style="margin-left: 25px;border-left:1px solid black">' . $key . ": ";
if (is_string($value))
$str .= $value;
else
$str .= RecursivePrettyPrint($value);
$str .= "</div>";
}
return $str;
}
// Class that simply turns an xml tree into a multilevel associative array
class XMLtoArray
{
private $root;
private $stack;
public function __construct()
{
$this->root = null;
$this->stack = array();
}
function ParseXML($feed_url)
{
$xml_parser = xml_parser_create();
xml_parser_set_option($xml_parser, XML_OPTION_CASE_FOLDING, 0);// or throw new Exception('Unable to Set Case Folding option on XML Parser!');
xml_parser_set_option($xml_parser, XML_OPTION_SKIP_WHITE, 1);// or throw new Exception('Unable to Set Skip Whitespace option on XML Parser!');
xml_set_object($xml_parser, $this);
xml_set_element_handler($xml_parser, "startElement", "endElement");
xml_set_character_data_handler($xml_parser, "characterData");
$fp = fopen($feed_url,"r");// or throw new Exception("Unable to read URL!");
while ($data = fread($fp, 4096))
xml_parse($xml_parser, $data, feof($fp));// or throw new Exception(sprintf("XML error: %s at line %d", xml_error_string(xml_get_error_code($xml_parser)), xml_get_current_line_number($xml_parser)));
fclose($fp);
xml_parser_free($xml_parser);
return $this->root;
}
public function startElement($parser, $tagName, $attrs)
{
if ($this->root == null)
{
$this->root = array();
$this->stack[] = &$this->root;
}
else
{
$parent = &$this->stack[count($this->stack)-1];
if (!is_array($parent))
$parent = array($parent);
if (isset($parent[$tagName]))
{
if (!is_array($parent[$tagName]))
$parent[$tagName] = array($parent[$tagName]);
}
else
$parent[$tagName] = null;
$this->stack[] = &$parent[$tagName];
}
}
public function endElement($parser, $tagName)
{
array_pop($this->stack);
}
public function characterData($parser, $data)
{
$data = trim($data);
$current = &$this->stack[count($this->stack)-1];
if (is_array($current))
$current[] = $data;
else
$current = $data;
}
}
?>
PHP代码2,无需认证
<?php
$contents = file_get_contents("http://www.whoisxmlapi.com//whoisserver/WhoisService?domainName=google.com&outputFormat=JSON");
//echo $contents;
$res=json_decode($contents);
if($res){
if($res->ErrorMessage){
echo $res->ErrorMessage->msg;
}
else{
$whoisRecord = $res->WhoisRecord;
if($whoisRecord){
echo "Domain name: " . print_r($whoisRecord->domainName,1) ."<br/>";
echo "Created date: " .print_r($whoisRecord->createdDate,1) ."<br/>";
echo "Updated date: " .print_r($whoisRecord->updatedDate,1) ."<br/>";
if($whoisRecord->registrant)echo "Registrant: <br/><pre>" . print_r($whoisRecord->registrant->rawText, 1) ."</pre>";
//print_r($whoisRecord);
}
}
}
?>
PHP代码3
<?php
$contents = file_get_contents("http://www.whoisxmlapi.com/whoisserver/WhoisService?domainName=google.com&cmd=GET_DN_AVAILABILITYoutputFormat=JSON");
// echo $contents;
$res=json_decode($contents);
if($res){
if($res->ErrorMessage){
echo $res->ErrorMessage->msg;
}
else{
$domainInfo = $res->DomainInfo;
if($domainInfo){
echo "Domain name: " . print_r($domainInfo->domainName,1) ."<br/>";
echo "Domain Availability: " .print_r($domainInfo->domainAvailability,1) ."<br/>";
//print_r($domainInfo);
}
}
}
?>