Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Auto backup cisco switches
# 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
You can’t perform that action at this time.