home *** CD-ROM | disk | FTP | other *** search
/ linuxmafia.com 2016 / linuxmafia.com.tar / linuxmafia.com / pub / linux / network / domain-check-1.9 < prev    next >
Text File  |  2007-07-19  |  13KB  |  377 lines

  1. #!/usr/bin/perl -ws
  2. # Created by Ben Okopnik on Thu Jun 28 09:11:52 EDT 2007
  3. #
  4. # Copyright (C) 2007 Ben Okopnik <ben@okopnik.com>
  5. # This program is free software; you can redistribute it and/or modify
  6. # it under the terms of the GNU General Public License as published by
  7. # the Free Software Foundation; either version 2 of the License, or
  8. # (at your option) any later version.
  9. #
  10. # This program is distributed in the hope that it will be useful,
  11. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. # GNU General Public License for more details.
  14.  
  15. =pod
  16. ################################## Changelog ##############################
  17.  
  18. 07/19/07 20:54 - v1.9
  19. * Added a little regex-fu to accept lines that have whitespace at the end
  20.  
  21. 07/19/07 11:56 - v1.8
  22. * Lots and lots of fixes for many different TLDs; much mangling of regexen.
  23. Now handles many more expiration date types than before. Most importantly,
  24. domains that don't list a registrar will now be displayed anyway (with a
  25. warning message); people probably know where to send their money, but not
  26. necessarily _when._
  27.  
  28. 07/04/07 12:28 - v1.7
  29. * Scrapped previous approach to the .org delay; the .orgs are now sorted to
  30.     the end of the domain list and all except the first one wait 20 seconds.
  31. * Added a cute little time ticker to the delay routine, just because. :)
  32.  
  33. 07/03/07  1:27 - v1.6
  34. * Added a rate limiter (4/minute) for .org domains
  35.  
  36. 06/30/07 18:34 - v1.5
  37. * Added a "domain not parseable; please report" warning
  38. * Added an "Unable to read 'whois' info" warning for the 'fgets: connection
  39.     reset by peer' error.
  40. * All expiration warnings are now sent as one email instead of one per
  41.     domain; ditto the expired domains notifications.
  42. * The 'printf' for the 'SKIPPED' error was ignoring the '-q' option; fixed
  43.  
  44. 06/30/07  8:19 - v1.4
  45. * Removed dependency on File::Find; searching PATH 'manually'
  46. * Added an 'exit 1' to the silent failure mode of 'croak'
  47.  
  48. 06/30/07  7:06 - v1.3
  49. * Improved the date-parsing regexes (the numerical months part can now only
  50.     match '01-12' instead of 'any two digits'); this should increase the
  51.     reliability of resolving 'dd-mm-yyyy' vs. 'mm-dd-yyyy' somewhat.
  52. * More accurate reporting for the 'SKIPPED' error (now shows exact reason)
  53. * Fixed the regexes that I screwed up while adding the Dotster extension
  54. * Added a '-v' option
  55.  
  56. 06/29/07 18:54 - v1.2
  57. * Got rid of an unnecessary system dependency ('which') - 'File::Find' is a
  58.     bit clunky, but better than depending on unknowns...
  59. * Another date-processing regex (ISOC-IL: 'validity: 29-06-2007')
  60.  
  61. 06/29/07 17:07 - v1.1
  62. * Modified output format to include both exp. date and days remaining
  63. * Added another date-processing regex (DOTSTER: 'Expires on: 29-Jun-07')
  64.  
  65. 06/29/07 15:06 - v1.0
  66. I'm finally willing to admit that this script is usable. :) Recent changes
  67. include:
  68.  
  69. * Parsing routine for "2007/08/12" date format
  70. * 'croak' notifies admin of problems encountered in silent mode
  71. * Added a fallback email address for 'croak'
  72. * Fixed GMT parsing routine miscalc (thanks to Rick Moen for the heads up)
  73.  
  74. ###########################################################################
  75. =cut
  76.  
  77. use strict;
  78. use Time::Local;
  79. $|++;
  80.  
  81. # Command-line variables
  82. our ($d, $e, $F, $h, $q, $s, $v, $x, $X);
  83.  
  84. ### FALLBACK ADDRESS FOR NOTIFICATION ############
  85. my $address = 'root@localhost';
  86. ##################################################
  87.  
  88. my ($name) = $0 =~ /([^\/]+)$/;
  89.  
  90. my $usage =<<"+EoT+";
  91. Usage: $name [-e=email] [-x=expir_days] [-q] [-h] <-d=domain_name|-F=domainfile>
  92.  
  93.   -d=domain        : Domain to analyze
  94.   -e=email_address : Send a warning message by email
  95.   -F=domain_list   : File with a list of domains, one per line
  96.   -h               : Print this message
  97.   -q               : Don't print to the console (REQUIRES '-e' OPTION)
  98.   -s=whois server  : Use alternate whois server
  99.   -v               : Display current version of this script
  100.   -x=days          : Change default (30d) expiration interval (REQUIRES '-e' OPTION)
  101.  
  102. +EoT+
  103.  
  104. # Locate 'whois'
  105. my ($whois) = grep -e, map "$_/whois", split /:/, $ENV{PATH};
  106. die "'whois' not found in path.\n" unless $whois;
  107.  
  108. # Find a mail client (mutt or mailx)
  109. my ($mail) = grep -e, map "$_/mutt", split /:/, $ENV{PATH};
  110. # Switch Mutt into 'mailx' mode if found
  111. if ($mail){
  112.     $mail .= " -x";
  113. }
  114. else {
  115.     ($mail) = grep -e, map "$_/mailx", split /:/, $ENV{PATH};
  116. }
  117. die "No 'mailx' or 'mutt' (mail client) found in path.\n" unless $mail;
  118.  
  119. # Read the version number at the top of the changelog
  120. if ($v){
  121.     seek DATA, 0, 0;
  122.     while (<DATA>){
  123.         if (m[^\d+/\d+/\d+[^v]+v([0-9.]+)]){
  124.             print "Version: $1\nCopyright (C) 2007 Ben Okopnik <ben\@okopnik.com>\n\n";
  125.             exit 0;
  126.         }
  127.     }
  128. }
  129.  
  130. # Email admin if '-q' is on; otherwise, just exit with the error
  131. sub croak {
  132.     if ($q){
  133.         # If '-e' wasn't specified, use the fallback address
  134.         $e ||= $address;
  135.         
  136.         # No place to send an error if this fails... :)
  137.         open Mail, "|$mail -s 'WARNING: $name script error' $e";
  138.         print Mail "$name [" . localtime() . "]: ", $_[0];
  139.         close Mail;
  140.  
  141.         exit 1;
  142.     }
  143.     else {
  144.         die $_[0];
  145.     }
  146. }
  147.  
  148. # Display the help output if requested or in case of incorrect usage
  149. die "$usage\n" if $h;
  150. die "\n*ERROR: '$name' requires an email address with the '-q' and the '-x' options*\n\n$usage" if ($q || $x) && ! $e;
  151. die "\n*ERROR: '$name' requires either a domain name or a domain list as an argument*\n\n$usage" if ! $d && ! $F;
  152.  
  153. # Set default notification interval to 30 days
  154. if ($x){
  155.     croak "Expiration interval must be specified in days (0-9999).\n"
  156.         unless $x =~ /^\d{1,4}$/;
  157. }
  158. else {
  159.     $x = 30;
  160. }
  161.  
  162. # Add the server to the "whois" command if it's been specified
  163. $whois .= " -h $s" if $s;
  164.  
  165. # Read the domain list file
  166. my @domains;
  167. if ($F){
  168.     croak "$F is not a regular file\n" unless -f $F;
  169.     croak "Can't read $F\n" unless -r _;
  170.     # Open the file if it exists
  171.     open F or croak "$F: $!\n";
  172.     while (<F>){
  173.         # Skip blank lines; ignore comments
  174.         next if /^\s*(?:#|$)/;
  175.         # Strip preceding and following blanks
  176.         s/^\s*(.*?)\s*$/$1/;
  177.         # Strip URI method
  178.         s#^.*://##;
  179.         push @domains, $_;
  180.     }
  181.     close F;
  182. }
  183.  
  184. # Having a '-F' AND a '-d' is explicitly not excluded
  185. if ($d){
  186.     # Strip URI method
  187.     $d =~ s#^.*://##;
  188.     push @domains, $d;
  189. }
  190.  
  191. # Sort list to push .orgs to the end; ASCIIbetical sort otherwise
  192. @domains = sort { ($a =~ /\.org$/i) <=> ($b =~ /\.org$/i) || $a cmp $b } @domains;
  193.  
  194. # Trim strings to specified length; return '**UNKNOWN**' if undef
  195. sub trim {
  196.     defined $_[0] || return "**UNKNOWN**";
  197.     substr($_[0], 0, $_[1]);
  198. }
  199.  
  200. # Lookup list for month number->name conversion
  201. my (%mth,%mlookup);
  202. @mth{map sprintf("%02d", $_), 1..12} = qw/jan feb mar apr may jun jul aug sep oct nov dec/;
  203. @mlookup{qw/January February March April May June July August September October November December/} =
  204.     qw/jan feb mar apr may jun jul aug sep oct nov dec/;
  205.  
  206. ########################## DATA COLLECTION SECTION #############################
  207.  
  208. # Process the domain list
  209. my ($seen, $msg, %list);
  210. for my $host (@domains){
  211.  
  212.     $q || print "Processing $host... ";
  213.  
  214.     # Delay to avoid triggering PIRs rate limiter
  215.     if ($host =~ /\.org$/i){
  216.         $q || print "\n\n*** Subsequent ORG domains get a 20-second delay due to rate limiting ***\n"
  217.             unless $seen;
  218.         # Show the cute little time ticker :)
  219.         if ($seen++){
  220.             my @chars = split //, '|/-\\';
  221.             for (1 .. 20){
  222.                 $q || print $chars[($_ - 1) % 4], "\b";
  223.                 sleep 1;
  224.             }
  225.         }
  226.         $q || print " ";
  227.     }
  228.  
  229.     $q || print "\n";
  230.  
  231.     # Execute the query
  232.     my $out;
  233.     open Who, "$whois $host|" or croak "Error executing $whois: $!\n";
  234.     {
  235.         # Read in the entire output of 'whois' as a single string
  236.         local $/;
  237.         $out = <Who>;
  238.     }
  239.     close Who;
  240.  
  241.     # 'fgets: connection reset by peer' - bloody annoying response!
  242.     if (!$out || $out !~ /domain/i){
  243.         print "Unable to read 'whois' info for $host. Skipping...\n";
  244.         next;
  245.     }
  246.  
  247.     # Freak out and run away if there's no match
  248.     if ($out =~ /no match/i){
  249.         $q || print "No match for $host!\n";
  250.         next;
  251.     }
  252.     # Ditto for bad hostnames
  253.     if ($out =~ /No whois server is known for this kind of object/i){
  254.         $q || print "'whois' doesn't recognize this kind of object.\n";
  255.         next;
  256.     }
  257.     
  258.     # Convert multi-line 'labeled block' output to 'Label: value'
  259.     $out =~ s/:\n(?!\n)/: /gsm if $out =~ /registrar:\n/i;
  260.  
  261.     # Date preprocessing. Desired date format is '29-jun-2007'
  262.     # 'Fri Jun 29 15:16:00 EDT 2007'
  263.     $out =~ s/(date:\s*| on:\s*)[A-Z][a-z]+\s+(...)\s+(\d+).*?(\d+)\s*$/$1$3-$2-$4/igsm;
  264.     # '29-Jun-07'
  265.     $out =~ s/(date:\s*| on:\s*)(\d{2})[\/ -](...)[\/ -](\d{2})\s*$/$1$2-$3-20$4/igsm;
  266.     # '2007-Jun-29'
  267.     $out =~ s/[^\n]*(?:date| on|expires on\.+):\s*(\d{4})[\/-](...)[\/-](\d{2})\.?\s*$/Expiration date: $3-$2-$1/igsm;
  268.     # '2007/06/29'
  269.     $out =~ s/(expires:\s*|date\s*:\s*| on:\s*)(\d{4})(?:[\/-]|\. )(0[1-9]|1[0-2])(?:[\/-]|\. )(\d{2})\.?\s*$/$1$4-$mth{$3}-$2/igsm;
  270.     # '29-06-2007'
  271.     $out =~ s/(?:validity:|expir(?:y|ation) date:|expires (?:on [^:]+:?|at:))\s*(\d{2})[\/-](0[1-9]|1[0-2])[\/-](\d{4})\s*[0-9:]*\s*\w*\s*$/Expiration date: $1-$mth{$2}-$3/igsm;
  272.     # '[Expires on]     2007-06-29' (.jp, .ru)
  273.     $out =~ s/(?:valid-date|expiration date:|paid-till:|\[expires on\])\s*(\d{4})[\/.-](0[1-9]|1[0-2])[\/.-](\d{2})\s*[0-9:]*\s*\w*\s*$/Expiration date: $3-$mth{$2}-$1/igsm;
  274.     # 'expires:     June  29 2007' (.is)
  275.     $out =~ s/expires:\s*([A-Z][a-z]+)\s+(\d{1,2})\s+(\d{4})\s*$/"Expiration date: " . sprintf("%02d", $2) . "-$mlookup{$1}-$3"/iegsm;
  276.     # 'renewal: 29-June-2007' (.ie)
  277.     $out =~ s/renewal:\s*(\d{1,2})[\/ -]([A-Z][a-z]+)[\/ -](\d{4})\s*$/Expiration date: $1-$mlookup{$2}-$3/igsm;
  278.     # 'expire:         20080315' (.cz, .ke)
  279.     $out =~ s/expir[ey]:\s*(\d{4})(\d{2})(\d{2})\s*$/Expiration date: $3-$mth{$2}-$1/igsm;
  280.     # 'domain_datebilleduntil: 2007-06-29T00:00:00+12:00' (.nz)
  281.     $out =~ s/domain_datebilleduntil:\s*(\d{4})[-\/](\d{2})[-\/](\d{2})T[0-9:+-]+\s*$/Expiration date: $3-$mth{$2}-$1/igsm;
  282.     # '29 Jun 2007 11:58:42 UTC' (.coop)
  283.     $out =~ s/((?:date|expires):\s*)(\d{2})[\/ -](...)[\/ -](\d{4})\s*[0-9:]*\s*\w*\s*$/$1$2-$3-$4/igsm;
  284.     # 'Record expires on 17/8/2100' (.hm)
  285.     $out =~ s/(?:expires on)\s*(\d{2})[\/-]([1-9]|0[1-9]|1[0-2])[\/-](\d{4})\s*[0-9:]*\s*\w*\s*$/"Expiration date: $1-".$mth{sprintf "%02d", $2} . "-$3"/iegsm;
  286.  
  287.  
  288.     # Debug mode, activated by '-X'
  289.     die "\n", "=" x 70, "\n", $out if $X;
  290.  
  291.  
  292.     # Collect the data from each query
  293.     for (split /\n/, $out){
  294.         # Clip pre- and post- blanks
  295.         s/^\s*(.*?)\s*$/$1/;
  296.         # Squash repeated tabs and spaces
  297.         tr/ \t//s;
  298.  
  299.         # This is where it all happens - regexes to capture registrar and expiration
  300.         $list{$host}{Registrar} ||= $1 if /(?:authorized agency|registrar)(?:\s*|_)(?:name|id)?:\s*(.*)$/i;
  301.         $list{$host}{Expires} ||= $1 if /(?:expires(?: on)?|expir(?:e|y|ation) date\s*|renewal(?:[- ]date)?)[:\] ]\s*(\d{2}-[a-z]{3}-\d{4})/i;
  302.         # print "Registrar: $list{$host}{Registrar}\nExpires: $list{$host}{Expires}\n";
  303.     }
  304.  
  305.     # Assign default message if no registrar was found
  306.     $list{$host}{Registrar} ||= "[[[ No registrar found ]]]";
  307.     
  308.     croak "No expiration date found in 'whois' output for $host. Please report this domain to the author!\n"
  309.         unless defined $list{$host}{Expires};
  310.  
  311.         # die "R: $list{$host}{Registrar} X: $list{$host}{Expires}\n";
  312. }
  313.  
  314. ########################## DATA ANALYSIS SECTION #############################
  315.  
  316. # Get current time snapshot in UTC
  317. my $now = timegm(gmtime);
  318.  
  319. # Convert dates to UTC epoch seconds; *will* fail on 19 Jan 2038. :)
  320. my %months;
  321. @months{qw/jan feb mar apr may jun jul aug sep oct nov dec/} = 0..11;
  322.  
  323. # Print the header if '$q' is off and there's content in %list
  324. $q || %list && printf "\n%-24s%-36s%s\n%s\n", "Host", "Registrar", "Exp.date/Days left", "=" x 78;
  325.  
  326. # Process the collected data
  327. my (%exp, %end);
  328. for my $k (sort keys %list){
  329.     unless (defined $list{$k}{Registrar} && defined $list{$k}{Expires}){
  330.         my $msg = "*** SKIPPED (missing ";
  331.         $msg .= ! defined($list{$k}{Registrar}) ? "reg. name) ***" : "exp. date) ***";
  332.         $q || printf "%-32s%s\n", trim($k, 31), $msg;
  333.         delete $list{$k};
  334.         next;
  335.     }
  336.     my @chunks = split /-/, $list{$k}{Expires};
  337.     my $epoch = timegm(0, 0, 0, $chunks[0], $months{lc $chunks[1]}, $chunks[2] - 1900);
  338.     my $diff = int(($epoch - $now) / 86400);
  339.     $q || printf "%-24s%-36s%-12s/%5s\n", trim($k, 23), trim($list{$k}{Registrar}, 35), 
  340.         $list{$k}{Expires}, $diff;
  341.  
  342.     # Prepare alerts if domain is expired or the expiration date is <= $x days
  343.     if ($e && ($diff <= $x)){
  344.         if ($diff <= 0){
  345.             $exp{$k} = -$diff; 
  346.         }
  347.         else {
  348.             $end{$k} = $diff;
  349.         }
  350.     }
  351. }
  352.  
  353. # Report expired domains
  354. if (%exp){
  355.     open Mail, "|$mail -s '$name: Expired domains' $e" or croak "$mail: $!\n";
  356.     print Mail "According to 'whois', the following domains have expired:\n\n";
  357.     for my $x (sort { $exp{$a} <=> $exp{$b} } keys %exp){
  358.         my $s = $exp{$x} == 1 ? "" : "s";
  359.         print Mail "$x ($exp{$x} day$s ago)\n";
  360.     }
  361.     close Mail;
  362. }
  363.  
  364. # Report domains that will expire within the '-x' period
  365. if (%end){
  366.     open Mail, "|$mail -s '$name: Domain expiration warning ($x day cutoff)' $e" or croak "$mail: $!\n";
  367.     print Mail "According to 'whois', these domains will expire soon:\n\n";
  368.     for my $d (sort { $end{$a} <=> $end{$b} } keys %end){
  369.         my $s = $end{$d} == 1 ? "" : "s";
  370.         print Mail "$d (in $end{$d} day$s)\n";
  371.     }
  372.     close Mail;
  373. }
  374.  
  375. __END__
  376.  
  377.