MysticRyuujin has asked for the wisdom of the Perl Monks concerning the following question:
I'm trying to create a module for connecting to our Cisco devices. My problem is that if I connect via the module the connection is closed when the module subroutine is done (I think.)
This is the first module I've ever tried to create. The login_auth subroutine works perfectly fine if I put it into the scrip directly, and it appears to do exactly what I want when I run it (it does log in and authenticate). However, the rest of the script doesn't do anything because it seems like the interactive session isn't being passed through. I have a lot of scripts for various things that use it over and over and I want to create a module to just call common subroutines like that.
The Script:
#!/usr/bin/perl -w use lib '/enm01/custom/scripts/modules'; use Expect; use cisco qw(&login_auth);; my $exp = new Expect; # Parces the BASH arugments into Perl variables ( $UNAME, $PWD, $ENABLE, $DNAME, $IP, $LOG ) = @ARGV; # This logs in and authenticates to the device login_auth(@ARGV); # This checks to make sure the hostname is correct namecheck(); sub namecheck { if ( $DNAME !~ /U....WX[0-9][0-9]/ ) { $exp->send("show run | include hostname\n"); @hostintval = $exp->expect( 10,"#"); $newmatch = $hostintval[3]; @hostname = split(m[ |\n],$newmatch); foreach(@hostname) { if ( ($_ !~ m/^hostname$|^show$|^run$|\||^include$|^$ +|\cM$/) ) { if ( $DNAME ne $_ ) { print LOG "$DNAME" . " is inco +rrect please change to " . "$_\n"; $DNAME = $_; } } } } }
The Module:
package cisco; use strict; use Exporter; use Expect; use vars qw( $VERSION @ISA @EXPORT @EXPORT_OK $UNAME $PWD $ENABLE $DNA +ME $IP $LOG $command $result $exp ); $VERSION = 1.00; @ISA = qw(Exporter); @EXPORT = (); @EXPORT_OK = qw(login_auth); ( $UNAME, $PWD, $ENABLE, $DNAME, $IP, $LOG ) = @ARGV; $exp = new Expect; open( LOG, ">>$LOG" ); sub login_auth { $command = "ssh $UNAME" . "@" . "$IP"; $exp->spawn($command) or die "Cannot spawn $command: $!\n"; my $connect = $exp->expect ( 30, [ qr/\(yes\/no\)\?\s*$/ => sub { $exp->send("yes\n"); +exp_continue; } ], [ qr/assword:\s*$/ => sub { $exp->send("$PWD\n"); } ], ); $result = $exp->expect(30, "#", ">"); if ($result == 2) { $exp->send("enable\n"); $result = $exp->expect(30, "assword:", "#"); if ($result == 1) { $exp->send("$ENABLE\n"); $result = $exp->expect(30, "assword:", "#"); if ($result == 1) { print LOG "Enable Password Rejected\n" +; exit(); } } } $exp->send("term len 0\n"); $exp->expect(10,"#"); } 1;
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: SSH connection with module
by NetWallah (Canon) on Mar 10, 2014 at 01:22 UTC | |
by MysticRyuujin (Novice) on Mar 10, 2014 at 01:40 UTC | |
by NetWallah (Canon) on Mar 10, 2014 at 03:39 UTC | |
by Anonymous Monk on Mar 10, 2014 at 04:34 UTC |