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