I have a few jumphosts that let I use to ssh into and then access network switches. I used to use rancid and have like 6 rancid instanes...no more. I wrote my own switch backup script. I wont go into the details of my script BUT i thought this ssh trick was worth a look with Perl.
Net::OpenSSH <--Awesome
This snippet of code does a ping check using a Jump Host. This is fairly easy to do using just ssh without Perl. But if I wanted to use Expect, I need Net::OpenSSH instance to pass into it.
The Modules I use for Expect are:
Mnet::Expect::Cli
Mnet::Expect::Cli::Ios
I actually wrap these in a MCE::Loop to do 10 or so switches at a time. MCE::Loop is always my go to for my loops that need to be sped up. Im pulling 30 switches in under a minute.
I am going to break up this snippet and explain whats going on.
Identify your two ips.
use Net::OpenSSH;
use Modern::Perl;
my $ip = '192.168.1.2'; #switch ip
my $proxy_ip = '10.90.3.2'; #jump host ip
sub pingCheck ( $ip, $proxy_ip) {
This example uses a ssh key pair, you can change key_path for password and put the ssh password in.
my %opts = (host => $proxy_ip, user => 'myuser', key_path => '/home/myuser/.ssh/id_rsa');
my $ssh_proxy = Net::OpenSSH->new(%opts);
$ssh_proxy->error and die "Couldn't establish SSH connection: ". $ssh_proxy->error;
Now I run a ping command on the jump host.
my @ping = $ssh_proxy->capture("ping -c 1 ".$ip);
foreach(@ping) {
if( $_ =~ m/^1\spackets transmitted/ && $_ =~ m/\s0\% packet loss/ ) {
return 1;
}
elsif($_ =~ m/^1\spackets transmitted/) {
return 0;
}
}
}
if(pingCheck()) {
warn "YES";
}
If i needed to access the $ip using a different port instead of ping, lets say it was telnet.
$ssh_proxy->system({ssh_opts => ['-O','forward','-L127.0.0.1:8000:'.$ip.':23']});
I can then do telnet localhost 8000
and it will connect to the $ip.
This might be confusing for some, its technical and geared for network engineers that can do programming. If you are interested in how i pull switches, you can ask and i'll hint at how to put something together.
Top comments (2)
Nice.
I personally prefer not to use
$_
explicitly. I'd either get rid of it, and I think in this code one could just write them/.../.../
statements without the$_ =~
and they would work, OR I'd use a variable with a meaningful name.I didnt know you could just do m/../../ i'll try that on monday and tweak it, im so used to using $_ for little loops but i should probably start using a named variable instead so people understand whats happening. Thanks! Good suggestions.