Wednesday, December 7, 2011

Perl SSH Log-in

Hi Folks, 

In the following post I will demonstrate a password-less login into Cisco appliance via the SSH protocol using a Perl script.

When combined with cron, it can be a great solution for saving your appliance configuration (show run) or checking status without the need to log-in into the appliance each time.

Pre requirements:
  • Perl
  • SSH client (duh!)
  • Net-SSH-Perl module

On Red-Hat (and friends) the module can be obtained via:
#yum install perl-Net-SSH-Perl -y 

Be sure to have a proper repository installed such as rpmforge 
Our simple script connects to the Cisco appliance via SSH and runs "show run" command (this account has enabled privilege).
The script itself should look like this:

#!/usr/bin/perl -w
use strict;
use warnings;
use Net::SSH::Perl;
my $ssh = Net::SSH::Perl->new('hostname');
$ssh->login('username', 'password');
my($out) = $ssh->cmd("show run");
print $out;

Since the script contains your appliance username & password don't forget to remove permissions for others:
#chmod o-rwx

Now, let's run the script:

Building configuration...

Current configuration : 8011 bytes
...more output ommited...

Works like charm!
Now, the only thing is left is to synchronize it with cron :)



Anonymous said...

Got the following error:

Use of uninitialized value $out in print at ./ line 9.

Anonymous said...

I put together a similar script, but I ran into a problem...

I need to enter into enable mode in order to execute a show run on our ciscos.

Any ideas how I can modify this script to allow me to enter the enable command and password ?

Iulian Stan said...

For everyone that encounter problems with this kind of script:

It seems the ssh v2 from cisco is not compatible with openssh.
switching to v1 the script works like a charm.