Last active
October 31, 2015 14:28
-
-
Save dinhoabreu/dfe4baab068e9c3f732a to your computer and use it in GitHub Desktop.
Whois formatter
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env php | |
<?php | |
function get(&$map, $pkeys, $default = '') { | |
$keys = explode('|', $pkeys); | |
foreach ($keys as $key) { | |
if (isset($map[$key])) { | |
return $map[$key]; | |
} | |
} | |
return $default; | |
} | |
function whois($ip) { | |
exec("whois $ip | iconv -f latin1", $lines); | |
$var_lines = array_filter($lines, function ($line) { | |
return !!preg_match('/^[^%][^:]+:/', $line); | |
}); | |
$vars = array('ip' => $ip); | |
foreach ($var_lines as $line) { | |
preg_match('/(^[^:]+):\s*(.*)\s*$/', $line, $matches); | |
$key = strtolower($matches[1]); | |
$value = $matches[2]; | |
$vars[$key] = $value; | |
} | |
return $vars; | |
} | |
function whois_format($vars, $format) { | |
$pattern = '/{([^}]+)}/'; | |
$replace = function ($matches) use ($vars) { | |
return get($vars, $matches[1]); | |
}; | |
return preg_replace_callback($pattern, $replace, $format); | |
} | |
function whois_reader($fd, $format) { | |
while (($line = fgets($fd)) != false) { | |
$ip = trim($line); | |
if (!empty($ip)) { | |
$vars = whois($ip); | |
echo whois_format($vars, $format) . PHP_EOL; | |
} | |
} | |
} | |
function main() { | |
$argv = $_SERVER['argv']; | |
$format_default = '{ip} ({inetnum|cidr}, {owner|orgname}, {ownerid|orgid}, {responsible|city}, {country})'; | |
$format = get($argv, 1, $format_default); | |
whois_reader(STDIN, $format); | |
} | |
main(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment