ericmisc has asked for the wisdom of the Perl Monks concerning the following question:

I have a simple perl expect script that does the following (1) ssh to an access gateway (2) from the gateway ssh to a router a run show commands on the router. All this works when (1) and (2) are part of the same subroutine. However, now I have to do step #2 on 10s of routers. Therefore I want to split (1) and (2) across separate functions. This is what I tried put it does not work:
use strict; use Expect; my $exp; sub sshGatewayLogin; sub getRtrinfo; { my %rtrList; $rtrList{chicago}{RTR}{R1}{IP} = '114.1.2.3'; $rtrList{chicago}{RTR}{R1}{PROMPT} = 'chicago-R1'; $rtrList{stlouis}{RTR}{R1}{IP} = '114.1.12.3'; $rtrList{stlouis}{RTR}{R1}{PROMPT} = 'stlouisR1'; sshGateway; foreach my $rtr (sort keys %rtrList) { getRtrInfo($rtr,\%rtrList); } $exp->soft_close(); } #--------------------------------------------------------------------- +---------- sub sshGatewayLogin { my $server = '110.10.10.2'; my $username = 'access'; my $pwd = 'xyz123'; my $port = 10568; my $cmd; my $timeout; my $before; my $after; #ssh to the gateway $cmd = "ssh $username\@$server -p $port"; print "dbg: cmd=$cmd\n"; $exp = Expect->spawn("$cmd") or die "Cannot spawn ssh command = $c +md\n"; $exp->log_user(0); $exp->expect(30, -re, 'password'); $exp->send("$pwd\n"); $exp->expect(20,"\$ "); } #--------------------------------------------------------------------- +---------- sub getRtrInfo { my ($rtr, $rtrList) = @_; my $cmd; my $pwd = 'pqr456'; #ssh to the router $cmd = 'ssh -o stricthostkeychecking=ask admin@' . $rtrList->{$rtr +}{RTR}{R1}{IP}; print "dbg: $cmd\n"; $exp->expect(30, -re, 'password'); $exp->send("$pwd\n"); $exp->log_file("$rtrList->{$rtr}{RTR}{R1}{PROMPT}.txt"); $exp->expect(30,-re, $rtrList->{$rtr}{RTR}{R1}{PROMPT}); $exp->send("show version\n"); $exp->expect(300,-re,$rtrList->{$rtr}{RTR}{R1}{PROMPT}); $exp->log_file(undef); }
The error I'm getting is "can't call method expect on an undefined value at line 65". Line 65 is first exp->expect statement is subroutine getRtrInfo. Please suggest a fix. thanks

Replies are listed 'Best First'.
Re: Perl Expect: passing the expect object
by toolic (Bishop) on Aug 02, 2012 at 16:58 UTC
    Change:
    sshGateway;

    to:

    sshGatewayLogin;

    I got a compile error until I made that change.

      Thank you toolic. I feel stupid now (: