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