1

Hope someone can help me here. Looking to redo my bash ssh script for cisco devices, and add on to it. Basically, my idea is to have an SSH to log me to the device in enable mode (so i can do regular admin stuff as usual ) and run in silent mode a backup of the device ( where the txt file is the hostname of the devices ) .

Best I have done so far , and haven`t test it on live equipment is :

#!/usr/bin/perl
use warnings;
use strict;
use Expect;
use Data::Dumper;

my $user = $ARGV[0];
my $pw = $ARGV[1];
my $host = $ARGV[2];
my $cmd = 'sh run';

my $exp = new Expect;
$exp->log_file("SSHLOGFILE.txt");#How do i make this to be the hostname of the device though
$exp->log_stdout(0);
$exp->raw_pty(1);


my $cli = "/usr/bin/ssh $user\@$host -o StrictHostKeyChecking=no -q $cmd";
#not sure about this 
$exp->spawn($cli) or die "Cannot spawn $cli: $!\n";

$exp->expect(5,
 [ qr /ssword:*/ => sub { my $exph = shift;
                          $exph->send("$pw\n");
                          exp_continue; }] );

my $read = $exp->exp_before();
chomp $read;
print Dumper($read);

$exp->soft_close();

I can install RANCID as i have no root on the jump host , I can run the scripts outside the jumphost , and Perl is my only option as I can have the modules on a local library.

Lillith
  • 11
  • 1

2 Answers2

1

The difference between a quickly written script and flexible robust automation is many lines of code and much testing. Rather than re-implement, consider using or extending existing modules that already do this. I found several in just a few minutes of searching.

In Perl, ciscodump (github) and the resulting Net::SSH2::Cisco.

If you can get Python on any host, Ansible ios_config can backup to a file with one task. While applying some config from a template.

John Mahowald
  • 30,009
  • 1
  • 17
  • 32
0

Using StrictHostKeyChecking=no is a very bad idea. Instead use option UserKnownHostsFile with a hosts file that contains the key of your target server(s). Just connect once manually with that option enabled to create it, so the server key is locked forever.

It looks like you're trying to use expect to feed a password to the SSH command. Once again this is a very bad idea. Use instead private key authentification and your password problem will just disappear. Or at least it is not anymore the problem of your script as loading private keys can be managed by an SSH agent.

Once you use private key authentication, I wonder if you'll even need that script at all as the bare ssh $user@$host sh run command will just do what you want.

dolmen
  • 138
  • 4