BackupRouters-TelnetToLocal.pl

#!/usr/bin/env perl
#=========================================================================
# BackupRouters-TelnetToLocal.pl
# VERSION: 1.0
# AUTHOR: Brian Steinmeyer
# EMAIL: [email protected]
# WEB: https://sigkillit.com
# DATE: 12/29/2012
# COMMENTS: Uses the Telnet::Cisco module to copy a Cisco Router's running
# configuration to the local machine. This module uses telnet so passwords
# will be in clear text. Pass the Cisco Router's DNS name or IP, logfile name,
# username, and password to the Sub. The script will back up the running
# config to the scripts location.
#=========================================================================
use Net::Telnet::Cisco;
use File::Basename;
use DateTime;

#Backup Routers
BackupRouterRunningConfig('192.168.1.1', 'router-config', 'USERNAME', 'PASSWORD');

sub BackupRouterRunningConfig {

    #Set Variables
    $router = $_[0];
    $logfile = $_[1] . DateTime->now()->strftime('%m-%d-%y_%H%M%S') . '.txt';
    $username = $_[2];
    $password = $_[3];

    #Login to Router
    print "\n\n" . $router . "\n*************************\n";
    my $session = Net::Telnet::Cisco->new(Host => $router, Errmode => "return");
    if(! $session->login($username, $password)) {
        print "ERROR Logging Into $router\n";
    } else {
        print "SUCCESS Logging Into $router\n";

        #Ensure Router is in Enabled Mode
        if($session->is_enabled == 1) {
            print "SUCCESS Router in Enabled Mode\n";

            #Avoid Autopaging
            $session->cmd('terminal length 0'); # Avoid Autopaging         

            #Grab Router Running-Config
            my @arrOutput = $session->cmd("show running-config");
            my $arrSize = @arrOutput;
            if($arrSize > 0) {
                print "SUCCESS backing up configuration\n";
                open FILE, ">", $logfile or die $!;
                print FILE @arrOutput;
                close FILE;
            } else {
                print "ERROR backing up configuration\n";
            }          
            $session->close;
        } else {
            print "ERROR Router Not in Enabled Mode\n";
        }
    }  
}