#!/usr/bin/perl use strict; use warnings; use Carp; use Net::SSH2; my %hosts = ( "MX200-1" => "10.10.8.128" ); my $DEBUG = 1; foreach my $name (sort keys %hosts) { my $ip = $hosts{$name}; $DEBUG && print "check $name ($ip)\n"; my $ssh2 = Net::SSH2->new(); if ($ssh2->connect($ip)) { $DEBUG && print "connected\n"; $ssh2->debug($DEBUG); $DEBUG && print "version=".join(', ', $ssh2->version())."\n"; $DEBUG && print "error=".$ssh2->error()."\n"; $ssh2->auth_list(); # Returns undef, auth_ok() will return 0 unless we call this(?) if ($ssh2->auth_ok()) { # Returns 4 (= true, we have been authenticated OK) $DEBUG && print "authenticated ok\n"; if (my $chan = $ssh2->channel()) { $DEBUG && print "channel open\n"; $chan->shell(); $chan->blocking(0); print $chan "admin\n"; print $chan "********\n"; # Password print $chan "enable\n"; print $chan "********\n"; # Enable password print get_response($chan); print $chan "set length 0\n"; print get_response($chan); print $chan "show configuration\n"; print get_response($chan); $chan->close; $DEBUG && print "done\n"; } else { croak "Error opening channel"; } } else { croak "Expected to be authenticated: ".$ssh2->auth_ok()."\n"; } $ssh2->disconnect; } else { warn "Error connecting to $name ($ip); please check host status\n"; } } sub get_response { my $chan = shift; my $res = ""; until ($res =~ /^\S+\#\s$/m) { # Keep reading until we see what looks like a prompt $res .= get_channel($chan); $DEBUG && print "res='$res'\n"; } return $res; } sub get_channel { my $chan = shift; my $output = ""; my $bytes = -1; until ($chan->eof || !defined $bytes) { $bytes = $chan->read(my $buffer, 1024); # Blocks unless we set $chan->blocking(0) $DEBUG && print "bytes=".($bytes || 'undef')."\n"; if (defined $bytes) { $DEBUG && print "buffer=$buffer\n"; $output .= $buffer; } } return $output; }