[BACK]Return to update_trango.pl CVS log [TXT][DIR] Up to [local] / trango / Net-Telnet-Trango / scripts

Diff for /trango/Net-Telnet-Trango/scripts/update_trango.pl between version 1.8 and 1.34

version 1.8, 2005/11/17 20:20:59 version 1.34, 2007/02/07 23:24:39
Line 1 
Line 1 
 #!/usr/bin/perl  #!/usr/bin/perl
 # $RedRiver: update_trango.pl,v 1.7 2005/11/17 20:09:45 andrew Exp $  # $RedRiver: update_trango.pl,v 1.33 2007/02/07 22:07:35 andrew Exp $
 ########################################################################  ########################################################################
 # update_trango.pl *** Updates trango foxes with a new firmware  # update_trango.pl *** Updates trango hosts with a new firmware
 #  #
 # 2005.11.15 #*#*# andrew fresh <andrew@mad-techies.org>  # 2005.11.15 #*#*# andrew fresh <andrew@mad-techies.org>
 ########################################################################  ########################################################################
 use strict;  # Copyright (C) 2005, 2006, 2007 by Andrew Fresh
 use warnings;  #
   # This program is free software; you can redistribute it and/or modify
 use Net::Telnet;  # it under the same terms as Perl itself.
 use Net::TFTP;  ########################################################################
 use Fcntl ':flock'; # import LOCK_* constants  use strict;
 #use YAML;  use warnings;
 use constant LOG_SAVE => 1;  
   use YAML qw/ LoadFile /;
   use Net::TFTP;
 my $config_file = shift || 'update_trango.conf';  use Net::Telnet::Trango;
 my $max_tries = 1;  
   my $config_file = shift || 'update_trango.yaml';
   my $max_tries = 3;
   
   my $l = Mylogger->new( { log_prefix => 'UT' } );
   
   $l->sp("Reading config file '$config_file'");
   my $conf = LoadFile($config_file);
 my $log_file =  GetLogName('UT');  
 my $MYLOG;  # file handle for logging so we don't have to close and open it all the time  my $hosts;
 END {  if (@ARGV) {
   if ($MYLOG) {      @{$hosts} = map { { name => $_, group => 'Trango-Client' } } @ARGV;
     mylog("Closing log ($log_file)");  }
     close $MYLOG;  else {
   }      $hosts = parse_hosts( $conf->{hosts} );
 }  }
   
   #@{ $hosts } = grep { $_->{name} eq '10.100.7.2' } @{ $hosts };
 mylog("Reading config file '$config_file'", LOG_SAVE);  
 my $conf = read_conf($config_file);  my $global_tries = $max_tries * 2;
   while ( $global_tries > 0 ) {
 mylog("  Hardware Type: $conf->{'type'}", LOG_SAVE);      $global_tries--;
 mylog("  File Name:     $conf->{'file_name'}", LOG_SAVE);      my $processed = 0;
 mylog("  File Size:     $conf->{'file_size'}", LOG_SAVE);  
 mylog("  File Checksum: $conf->{'file_cksum'}", LOG_SAVE);      foreach my $host ( @{$hosts} ) {
 mylog("  FW Version:    $conf->{'ver'}", LOG_SAVE);  
 mylog("  FW Checksum:   $conf->{'cksum'}", LOG_SAVE);          if ( !exists $host->{retry} ) {
 mylog("", LOG_SAVE);              $host->{tries} = 0;
               $host->{retry} = 1;
           }
   
           if ( $host->{tries} >= $max_tries ) {
               $host->{retry} = 0;
           }
 foreach my $fox (@{ $conf->{'ips'} }) {  
   mylog("Updating: $fox", LOG_SAVE);          if ( $host->{retry} <= 0 ) {
               next;
   ## Connect and login.          }
   my $host = new Net::Telnet (Timeout => 5,  
                               Prompt => '/#> *$/');          $host->{tries}++;
   mylog("Connecting to $fox");          $processed++;
   unless ( $host->open( Host => $fox, Errmode => 'return') ) {  
     mylog("Couldn't connect to $fox.  Connection timed out.", LOG_SAVE);          $l->sp("");
     next;          $l->sp("Checking: $host->{name} (try $host->{tries})");
   }          my $needs_reboot = 0;
   $host->dump_log('dump.log');  
           ## Connect and login.
   ## Login to remote host.          my $t = new Net::Telnet::Trango(
   unless ($host->waitfor(              Timeout => 5,
     -match => '/password: ?$/i',              Errmode => 'return',
     -errmode => "return",          ) or die "Couldn't make new connection: $!";
   ) ) {          $l->p("Connecting to $host->{name}");
     mylog("problem connecting to host ($fox): " . $host->lastline, LOG_SAVE);          unless ( $t->open( $host->{name} ) ) {
     next;              $l->sp("Error connecting: $!");
   }              next;
           }
   my $login_banner = $host->lastline;  
   my ($type, $version) = $login_banner =~          my $password = $host->{Telnet_Password} || $conf->{general}->{password};
     /Welcome to Trango Broadband Wireless (\w+)-(.+)$/i;  
           $l->p("Logging in");
   if ($type ne $conf->{'type'}) {          $t->login($password);
     mylog("Wrong type of unit ('$type' should be '$conf->{'type'}')", LOG_SAVE);          unless ($t->logged_in) {
     $host->close;              $l->p('Failed!');
     next;              $t->close;
   }              next;
           }
   if ($version eq $conf->{'ver'}) {  
     mylog("Already up to date with firmware version '$version'", LOG_SAVE);          $l->sp("Getting sudb");
     $host->close;          my $sudb = $t->sudb_view;
     next;          if ($sudb) {
   }              foreach my $su (@{ $sudb }) {
                   $l->p("Getting su info $su->{suid}");
   mylog("Logging in");                  my $su_info = $t->su_info( $su->{suid} );
   $host->print($conf->{'password'});                  if ($su_info->{ip}) {
   unless ($host->waitfor(                      if (grep { $_->{name} eq $su_info->{'ip'} } @{ $hosts }) {
     -match => $host->prompt,                          $l->p("Already have $su_info->{ip}");
     -errmode => "return",                          next;
   ) ) {                      }
     mylog("login ($fox) failed: " . $host->lastline);                      $l->sp("Adding host $su_info->{ip}");
     next;                      my $new_host = {
   }                          password => $host->{password},
                           name     => $su_info->{ip},
                           remarks  => $su_info->{remarks},
   mylog("Sending commands");                      };
   ## Send commands                      push @{ $hosts }, $new_host;
   if ( upload($host, $fox, $conf->{'file_name'}) ) {                  } else {
     mylog("Rebooting");                      $l->sp("Couldn't get su info for $su->{suid}");
     $host->print("reboot\n");                      $l->sp("ERR: " . $t->last_error);
     $host->getline;                  }
   } else {              }
     mylog("Exiting");          }
     $host->print("exit\n");  
     $host->getline;          foreach my $firmware_type ( 'Firmware', 'FPGA' ) {
   }  
   $host->close;              if ( !exists $conf->{$firmware_type} ) {
   mylog("", LOG_SAVE);                  $l->s("No configs for '$firmware_type'");
 }                  next;
               }
 sub upload  
 {              my $host_type = $t->host_type;
   my $host = shift;              if ( $firmware_type eq 'FPGA' ) {
   my $fox  = shift;                  $host_type =~ s/\s.*$//;
   my $file = shift;              }
   
   mylog("Getting current version");              if ( !exists $conf->{$firmware_type}->{$host_type} ) {
   my $ver = get_ver($host);                  $l->sp("No '$firmware_type' config for type $host_type");
                   next;
   if (              }
     $ver->{'Firmware Version'}  eq $conf->{'ver'} &&  
     $ver->{'Firmware Checksum'} eq $conf->{'cksum'}              if (   $firmware_type eq 'Firmware'
   ) {                  && $t->firmware_version eq
     mylog("Already updated!", LOG_SAVE);                  $conf->{$firmware_type}->{$host_type}->{ver} )
     return 1;              {
   }                  $l->sp("Firmware already up to date");
                   next;
   my $try = 0;              }
   while (1) {  
     if ($try >= $max_tries) {              if ( !$t->logged_in ) {
       mylog("Couldn't update in $max_tries tries!");                  $l->p("Logging in");
       return undef;                  $t->login($password);
     }                  unless ($t->logged_in) {
     $try++;                      $l->p('Failed!');
                       $t->close;
     #sysinfo($host);                      last;
                       }
     mylog("Enabling TFTPd");              }
     enable_tftpd($host) || die "Couldn't enable tftpd";  
               foreach my $k ( keys %{ $conf->{general} } ) {
     mylog("Uploading file ($file)");                  $conf->{$firmware_type}->{$host_type}->{$k} ||=
     # use tftp to push the file up                    $conf->{general}->{$k};
     my $tftp = Net::TFTP->new($fox, Mode => 'octet');              }
               $conf->{$firmware_type}->{$host_type}->{firmware_type} ||=
     $tftp->put($file, $file)                $firmware_type;
       or die "Error uploading: " . $tftp->error;              $conf->{$firmware_type}->{$host_type}->{type} = $host_type;
   
     # waitfor some sort of output              $l->sp("$host_type $firmware_type");
     # make sure it says 'Success.' otherwise error              ## Send commands
     #print "LAST: " . $host->lastline;              my $rc = upload( $t, $conf->{$firmware_type}->{$host_type} );
     #my @lines = $host->getlines;              if ($rc) {
     #print Dump \@lines;                  $l->sp("Successfull!");
                       $host->{retry}--;
     mylog("Checking upload ($conf->{'file_cksum'})");                  $needs_reboot = 1;
     my $results = check_tftpd($host);              }
     # check the 'File Length' against ???              elsif ( defined $rc ) {
     if ( $results->{'File Checksum'} ne $conf->{'file_cksum'}) {                  $l->sp("Already up to date");
       mylog("File checksum does not match config file!", LOG_SAVE);                  $host->{retry}--;
       next;              }
     }              else {
     mylog("File checksum ($results->{'File Checksum'}) " .                  $l->sp("Failed! - Bye $host->{name}");
           "matches ($conf->{'file_cksum'})");                  $l->e("Error updating $firmware_type on $host->{name}" .
                       "(try $host->{tries})");
     if ($results->{'File Length'}   !~ /^$conf->{'file_size'} bytes/) {                  $t->bye;
       mylog("File length does not match config file!", LOG_SAVE);                  # don't try any other firmware, don't want to reboot
       next;                  last;
     }              }
     mylog("File length ($results->{'File Length'}) " .  
           "matches ($conf->{'file_size'})");          }
   
     if ( uc($results->{'File Name'}) ne uc($conf->{'file_name'}) ) {          if ($needs_reboot) {
       mylog("File name does not match config file!", LOG_SAVE);              $l->sp("Rebooting $host->{name}");
       next;              $t->reboot;
     }          }
     mylog("File name ($results->{'File Name'}) " .          else {
           "matches ($conf->{'file_name'})");              $l->sp("Bye $host->{name}");
               $t->bye();
     mylog("Updating flash (new checksum '$conf->{'cksum'}')");          }
     $results = updateflash(      }
       $host, $ver->{'Firmware Checksum'}, $conf->{'cksum'}  
     ) or die "Couldn't update flash: " . $host->lastline;      if ( !$processed ) {
     unless (          $l->sp("");
       defined $results->{'Checksum'} &&          $l->sp("Finished.  No more hosts.");
       $results->{'Checksum'} eq $conf->{'cksum'}          last;
     ) {      }
       mylog("Saved checksum does not match config file!", LOG_SAVE);  }
       next;  
     }  sub upload {
     mylog("Uploaded checksum ($results->{'Checksum'}) " .      my $t    = shift;
           "matches ($conf->{'cksum'})");      my $conf = shift;
       
     mylog("Successfully updated!", LOG_SAVE);      my $file = $conf->{firmware_path} . '/' . $conf->{file_name};
     return 1;  
   }      my $fw_type = $conf->{firmware_type};
 }  
       my $ver = $t->ver;
 sub get_ver  
 {      if (
   my $host = shift;          !(
   return cmd($host, 'ver');              $ver->{ $fw_type . ' Version' } && $ver->{ $fw_type . ' Checksum' }
 }          )
         )
 sub enable_tftpd      {
 {          $l->sp("Error getting current version numbers");
   my $host = shift;          return;
       }
   my $vals = cmd($host, 'tftpd on', 'Success.');  
       if (   $ver->{ $fw_type . ' Version' } eq $conf->{'ver'}
   if ($vals->{'Tftpd'} eq 'listen') {          && $ver->{ $fw_type . ' Checksum' } eq $conf->{'cksum'} )
     return $vals;      {
   } else {          return 0;
     return undef;      }
   }  
 }      $l->sp("Updating $fw_type");
       $l->sp("Config information:");
 sub check_tftpd      $l->sp("  Hardware Type: $conf->{'type'}");
 {      $l->sp("  File Name:     $conf->{'file_name'}");
   my $host = shift;      $l->sp("  File Size:     $conf->{'file_size'}");
   return cmd($host, 'tftpd', 'Success.');      $l->sp("  File Checksum: $conf->{'file_cksum'}");
 }      $l->sp("  Conf Version:  $conf->{'ver'}");
       $l->sp("  Cur  Version:  $ver->{$fw_type . ' Version'}");
 sub sysinfo      $l->sp("  Conf Checksum: $conf->{'cksum'}");
 {      $l->sp("  Cur  Checksum: $ver->{$fw_type . ' Checksum'}");
   my $host = shift;  
   return cmd($host, 'sysinfo', 'Success.');      my $try = 0;
 }      while (1) {
           if ( $try >= $max_tries ) {
 sub updateflash              $l->sp("Couldn't update in $max_tries tries!");
 {              return;
   my $host = shift;          }
   my $old = shift;          $try++;
   my $new = shift;  
           $l->p("Enabling TFTPd");
   return undef unless $new;          unless ( $t->enable_tftpd ) {
               $l->sp("Couldn't enable tftpd");
   return cmd($host, "updateflash mainimage $old $new", 'Success.', 90);              next;
 }          }
   
 sub cmd          $l->p("Uploading file ($conf->{file_name})");
 {  
   my $host   = shift;          # use tftp to push the file up
   my $string = shift;          my $tftp = Net::TFTP->new( $t->Host, Mode => 'octet' );
   my $expect_last = shift;  
   my $timeout = shift || 5;          unless ( $tftp->put( $file, $file ) ) {
               $l->sp( "Error uploading: " . $tftp->error );
   my @lines = $host->cmd(String => $string, Timeout => $timeout);              next;
           }
   my $vals = decode_lines(@lines);  
           $l->p("Checking upload ($conf->{'file_cksum'})");
   my $last = $host->lastline;          my $results = $t->tftpd;
   
   unless ($expect_last) {          # check the 'File Length' against ???
     return $vals;          if (
   }              !(
                      $results->{'File Checksum'}
   if ($last =~ /$expect_last$/) {                  && $results->{'File Length'}
     return $vals;                  && $results->{'File Name'}
   } else {              )
     warn "Error with command ($string): $last";            )
     return undef;          {
   }              $l->sp("Unable to get results of upload");
 }              next;
           }
 sub decode_lines          if ( $results->{'File Checksum'} ne $conf->{'file_cksum'} ) {
 {              $l->sp( "File checksum ("
   my @lines = @_;                    . $results->{'File Checksum'}
                     . ") does not match config file ("
   my %conf;                    . $conf->{'file_cksum'}
                     . ")!" );
   my $key = '';              next;
   my $val = '';          }
   my $in_key = 0;          $l->p("File checksum matches . . . ");
   my $in_val = 0;  
           if ( $results->{'File Length'} !~ /^$conf->{'file_size'} bytes/ ) {
   foreach my $line (@lines) {              $l->sp( "File length ("
     my @chars = split //, $line;                    . $results->{'File Length'}
                     . ") does not match config file ("
     my $last_key = '';                    . $conf->{'file_size'}
     foreach my $c (@chars) {                    . " bytes)!" );
               next;
       if ($c eq '[' || $c eq "\r" || $c eq "\n") {          }
         if ($c eq '[') {          $l->p("File length matches . . . ");
           $in_key = 1;  
           $in_val = 0;          if ( uc( $results->{'File Name'} ) ne uc($file) ) {
         } else {              $l->sp( "File name ("
           $in_key = 0;                    . $results->{'File Name'}
           $in_val = 0;                    . ") does not match config file ("
         }                    . $file
                     . ")!" );
         if ($key) {              next;
           $key =~ s/^\s+//;          }
           $key =~ s/\s+$//;          $l->p("File name matches . . . ");
   
           $val =~ s/^\s+//;          my $image_type = 'mainimage';
           $val =~ s/\s+$//;          if ( $fw_type eq 'FPGA' ) {
               $image_type = 'fpgaimage';
           if ($key eq 'Checksum' && $last_key) {          }
             # Special case for these bastids.          $l->p("Updating $image_type (new checksum '$conf->{'cksum'}')");
             my $new = $last_key;          unless (
             $new =~ s/\s+\S+$//;              $results = $t->updateflash(
             $key = $new . " " . $key;                  args => $image_type . ' '
           }                    . $ver->{ $fw_type . ' Checksum' } . ' '
                     . $conf->{'cksum'},
           $last_key = $key;                  Timeout => 90,
           $conf{$key} = $val;              )
           $key = '';            )
           $val = '';          {
         }              $l->sp("Couldn't update flash: $!");
               next;
       } elsif ($c eq ']') {          }
         $in_val = 1;  
         $in_key = 0;          unless ( defined $results->{'Checksum'}
         $c = shift @chars;              && $results->{'Checksum'} eq $conf->{'cksum'} )
           {
       } elsif ($in_key) {              $l->sp( "Saved checksum "
         $key .= $c;                    . $results->{'Checksum'}
                     . " does not match config file "
       } elsif ($in_val) {                    . $conf->{'cksum'}
         $val .= $c;                    . "!" );
       }              next;
     }          }
   }  
   #print Dump \%conf;          $l->p("$fw_type saved checksum matches . . . ");
   
   if (%conf) {          return 1;
     return \%conf;      }
   } else {  }
     return \@lines;  
   }  sub parse_hosts {
 }      my $src = shift;
   
 sub read_conf      my @hosts;
 {      foreach my $h ( @{$src} ) {
   my $file = shift;          if ( $h->{name} =~ /^(\d{1,3}\.\d{1,3}\.\d{1,3}\.)(\d{1,3})-(\d{1,3})/ )
   my %conf;          {
   my $in_ip_list = 0;              for ( $2 .. $3 ) {
   open my $fh, $file or die "Couldn't open file $file: $!";                  my %cur_host;
   while (<$fh>) {                  foreach my $k ( keys %{$h} ) {
     chomp;                      $cur_host{$k} = $h->{$k};
     next if /^#/;                  }
     next if /^$/;                  $cur_host{name} = $1 . $_;
     if ($in_ip_list) {                  if ( !grep { $cur_host{name} eq $h->{name} } @hosts ) {
       if (/^(\d{1,3}\.\d{1,3}\.\d{1,3}\.)(\d{1,3})-(\d{1,3})/) {                      push @hosts, \%cur_host;
         push @{ $conf{'ips'} }, $1 . $_ for ($2..$3);                  }
       } else {              }
         push @{ $conf{'ips'} }, $_;          }
       }          else {
     } else {              push @hosts, $h;
       my ($key, $val) = split /\s+/, $_, 2;          }
       }
       if (lc($key) eq 'ips') {  
         $in_ip_list = 1;      return \@hosts;
         next;  }
       }  
   package Mylogger;
       $conf{ lc($key) } = $val;  
     }  use Fcntl ':flock';    # import LOCK_* constants
   }  
   close $fh;  #use YAML;
   use constant LOG_PRINT => 128;
   #print Dump \%conf;  use constant LOG_SAVE  => 64;
   foreach (  use constant LOG_ERR   => 1;
     'password',  
     'file_name', 'file_size', 'file_cksum',  DESTROY {
     'ver', 'cksum', 'ips',      my $self = shift;
   ) {      if ( $self->{'MYLOG'} ) {
     die "No $_ specified in config file!"          $self->p("Closing log ($self->{'log_path'}/$self->{'log_file'})");
       if (not exists $conf{$_});          close $self->{'MYLOG'};
   }      }
   }
   #print Dump \%conf;  
   #exit;  sub new {
   return \%conf;      my $package = shift;
 }      my $self = shift || {};
   
 sub mylog      $self->{'base_path'}  ||= '.';
 {      $self->{'log_path'}   ||= $self->{'base_path'};
   my $thing = shift;      $self->{'log_prefix'} ||= 'LOG';
   chomp $thing;      $self->{'log_file'} ||=
   my $save = shift;        GetLogName( $self->{'log_prefix'}, $self->{'log_path'} );
       bless $self, $package;
   print $thing, "\n";  }
   
   if (defined $save && $save == LOG_SAVE) {  sub s {
     unless ($MYLOG) {      my $self = shift;
       open ($MYLOG, '>>', $log_file)      my $m    = shift;
         or die "Couldn't open logfile!\n";      return $self->mylog( $m, LOG_SAVE );
       my $ofh = select $MYLOG;  }
       $|=1;  
       select $ofh;  sub p {
       mylog("Opened log ($log_file)");      my $self = shift;
     }      my $m    = shift;
       return $self->mylog( $m, LOG_PRINT );
     flock($MYLOG, LOCK_EX);  }
     print $MYLOG (scalar gmtime), "\t", $thing, "\n"  
       or die "Couldn't print to MYLOG: $!";  sub sp {
     flock($MYLOG, LOCK_UN);      my $self = shift;
   }      my $m    = shift;
 }      return $self->mylog( $m, LOG_SAVE | LOG_PRINT );
   }
 sub GetLogName  
 {  sub e {
   my $prefix  = shift || die "Invalid prefix passed for log";      my $self = shift;
       my $m    = shift;
   my $logdate = GetLogDate();      return $self->mylog( $m, LOG_ERR );
   my $logver  = 0;  }
   my $logname;  
   sub mylog {
   do {      my $self = shift;
     $logname = $prefix . $logdate . sprintf("%02d", $logver) . '.log';  
     $logver++;      my $thing = shift;
   } until (not -e $logname);      chomp $thing;
   
   return $logname;      my $which = shift;
 }  
       my $MYLOG;
 sub GetLogDate      if ( $which & LOG_PRINT ) {
 {          print $thing, "\n";
   my ($sec,$min,$hour,$mday,$mon,$year,,,) = localtime();      }
   
   $mon++;      if ( $which & LOG_SAVE ) {
   $year += 1900;          if ( $self->{'MYLOG'} ) {
               $MYLOG = $self->{'MYLOG'};
   if ($min  < 10) { $min  = "0$min"  }          }
   if ($sec  < 10) { $sec  = "0$sec"  }          else {
   if ($hour < 10) { $hour = "0$hour" }              unless ($MYLOG) {
   if ($mday < 10) { $mday = "0$mday" }                  open( $MYLOG, '>>',
   if ($mon  < 10) { $mon  = "0$mon"  }                      $self->{'log_path'} . '/' . $self->{'log_file'} )
                     or die "Couldn't open logfile!\n";
   my $time = $year . $mon . $mday;                  my $ofh = select $MYLOG;
                   $| = 1;
   return $time;                  select $ofh;
 }                  $self->{'MYLOG'} = $MYLOG;
   
                   $self->p(
                       "Opened log ($self->{'log_path'}/$self->{'log_file'})");
               }
           }
           flock( $MYLOG, LOCK_EX );
           print $MYLOG ( scalar gmtime ), "\t", $thing, "\n"
             or die "Couldn't print to MYLOG: $!";
           flock( $MYLOG, LOCK_UN );
       }
   
       if ( $which & LOG_ERR ) {
           # XXX Could tie in here to handle some sort of notifications.
           print STDERR $thing, "\n";
       }
   }
   
   sub GetLogName {
       my $prefix = shift || die "Invalid prefix passed for log";
   
       my $logdate = GetLogDate();
       my $logver  = 0;
       my $logname;
   
       do {
           $logname = $prefix . $logdate . sprintf( "%02d", $logver ) . '.log';
           $logver++;
       } until ( not -e $logname );
   
       return $logname;
   }
   
   sub GetLogDate {
       my ( $sec, $min, $hour, $mday, $mon, $year,,, ) = localtime();
   
       $mon++;
       $year += 1900;
   
       if ( $min  < 10 ) { $min  = "0$min"  }
       if ( $sec  < 10 ) { $sec  = "0$sec"  }
       if ( $hour < 10 ) { $hour = "0$hour" }
       if ( $mday < 10 ) { $mday = "0$mday" }
       if ( $mon  < 10 ) { $mon  = "0$mon"  }
   
       my $time = $year . $mon . $mday;
   
       return $time;
   }

Legend:
Removed from v.1.8  
changed lines
  Added in v.1.34

FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>