全部博文(1144)
分类: LINUX
2009-12-09 11:47:13
#!/usr/local/bin/perl use strict; use Net::Telnet::Cisco; my $un = 'username'; # generic username my $pw = 'password'; # generic password my $dir = '/usr/sys/routers/'; # make subdirectories in $dir called the FQDN of the routers you want to back up # if you need seperate credentials for this router, # inside those subdirectories, in a file called Override put: #un: username #pw: password #en: enable_password my $time = time(); opendir(D, $dir) || die "cannot opendir $dir: $!\n"; foreach my $router (grep {!/^\./} readdir D){ my %credentials; if(open(O, "${dir}/${router}/Override")){ while(){ chomp; if(/^(un|pw|en):\s(.+)/){ $credentials{$1} = $2; }else{ warn "unknown syntax in ${dir}/${router}/Override\n"; } } close O; } $credentials{un} = $un unless(exists($credentials{un})); $credentials{pw} = $pw unless(exists($credentials{pw})); $credentials{en} = $pw unless(exists($credentials{en})); opendir(S, "${dir}/${router}/") || die "cannot opendir ${dir}/${router}/: $!\n"; my $last_file; foreach my $file (sort grep {/^\d/} readdir S){ if((stat(${dir}/${router}/${file}))[9] < ($time-5184000)){ # file is older than 60 days warn "$router/$file is older than 60 day\n"; #unlink(${dir}/${router}/${file}) || warn "could not unlink $router/$file: $!\n"; } $last_file = $file; } closedir S; my $telnet = Net::Telnet::Cisco->new(Host=>$router,Prompt => '/[\$%#>]\s*$/',Timeout=>5); die "could not connect to $router\n" unless($telnet); $telnet->login($credentials{un},$credentials{pw}); unless($telnet->is_enabled){ unless($telnet->enable($credentials{en})){ die "Cant enable: " . $telnet->errmsg; } } $telnet->cmd("term len 0"); my @result = $telnet->cmd("sho run"); $telnet->cmd(""); $telnet->print("exit"); die "i think we have a bad config" unless(@result > 25); foreach(1..3){ shift @result; }; # garbage foreach(1..2){ pop @result; }; # more garbage open(O, "${dir}/${router}/${last_file}") || die "canont open $router/${last_file}: $!\n"; my $diff; my $n = 0; while( ){ unless(/^ntp clock-period/ || /^\!/){ unless($_ eq $result[$n]){ $diff = 1; last; } } $n++; } close O; if($diff){ chop(my $date=`date '+%Y%m%d'`); open(N, ">${dir}/${router}/${date}.config") || die "cannot write to $dir/$router/$date.config: $!\n"; foreach(@result){ print N; } close N; } } closedir D;