Last active
April 18, 2020 23:46
-
-
Save AlexAvlonitis/005e5e91f160fea9e913 to your computer and use it in GitHub Desktop.
Auto backup cisco switches
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# https://github.com/alexavlonitis | |
# to use this script run perl cisco_backup.pl "cisco enable password" # | |
use Net::SSH2; | |
use Net::Telnet::Cisco; | |
use warnings; | |
use strict; | |
my $user = "username"; #username of your switches | |
my $password = $ARGV[0]; #argument for the password | |
my $tftp = "x.x.x.x"; #ip address of the tftp server | |
# array with all the ip addresses of the switches | |
#replace x.x.x.x with the IPs of your switches | |
my @switches = qw( | |
x.x.x.x | |
x.x.x.x | |
x.x.x.x | |
x.x.x.x | |
x.x.x.x | |
); | |
foreach my $line (@switches) { | |
chomp($line); # clear whitespaces | |
my $ssh2 = 1; | |
eval { | |
my $cs = Net::Telnet::Cisco->new( Host =>$line, Timeout => 45); | |
if (!$cs->login($user, $password)) # Login | |
{ | |
print "Error connecting to $line\n"; | |
}else { | |
print "Opening Telnet session to $line\n"; | |
$ssh2 = 0; # If telnet worked, no need to ssh | |
$cs->enable($password); | |
$cs->cmd("copy system:/running-config tftp://$tftp/$line.config\n\n\n"); | |
print "$line has been backed up\n"; | |
$cs->close; # Log out of device | |
} | |
}; | |
if ($ssh2 == 1){ | |
my $ssh = Net::SSH2->new(); | |
$ssh->debug(0); #put 1 to debug ssh connection if there is a problem | |
if(!$ssh->connect($line)){ | |
print("Connection Failed $line\n "); | |
last; | |
}else { | |
print("connection succeeded $line\n"); | |
} | |
if(!$ssh->auth_password($user,$password)){ | |
print("Authentication Failed"); | |
exit(1); | |
}else { | |
print("Authenticated to: $line\n"); | |
} | |
my $channel = $ssh->channel(); | |
$channel->blocking(0); | |
$channel->shell(); | |
print $channel "copy running-config tftp://$tftp/$line.config\n\n\n"; | |
print ("$line has been backed up\n"); | |
sleep 1; # without this it doesn't work, need to wait 1 sec before it goes to the next ip | |
$channel->close; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment