Hi everyone,
I have given up finally trying to find a way to do this.
I have a subroutine called LoginFirst where I am starting a new SSH session.
I have bunch of subroutines, each one of them uses a (or I have to create
a new SSH constructor everytime) ssh connection to get some value so
what I did is use LoginFirst to first start a ssh and then re-use the handle
in all other subroutines but does not seem to be working, can someone please help.
sub LoginFirst {
my $ssh = Net::SSH::Expect->new (
host => $self->{ipaddr},
password=> $self->{Password},
user => $self->{UserName},
raw_pty => 1,
timeout => 10
);
return $ssh;
}
sub DeviceVersion {
my $newssh = LoginFirst();
my @commands = ("enable","show version");
my $commands = join "\n", @commands;
my $prout = $newssh->exec($commands);
print " $prout\n";
}
A quick demo of how to wrap the SSH::Expect object in a class of your own (seems to be what you were doing). You were missing the constructor so I added one, you called the LoginFirst routine with no object, whereas you depend on $self existing in it and you forgot to login
#!/usr/bin/perl
package RunRemote;
use strict;
use warnings;
use Net::SSH::Expect;
sub new{
my $proto=shift;
my %args=@_;
my $class = ref($proto) || $proto;
my $self;
$self->{ipaddr} = defined $args{ipaddr}?$args{ipaddr}:"127.0.0.1";
$self->{Password} = $args{Password};
$self->{UserName} = defined $args{UserName}?$args{UserName}:$ENV{USER};
bless ($self,$class);
}
sub LoginFirst {
my $self=shift;
my $ssh = Net::SSH::Expect->new (
host => $self->{ipaddr},
password => $self->{Password},
user => $self->{UserName},
raw_pty => 1,
timeout => 10
);
$ssh->login();
return $ssh;
}
sub DeviceVersion {
my $self=shift;
my $newssh = $self->LoginFirst();
#my @commands = ("enable","show version");
my @ commands = @_;
my $commands = join "\n", @commands;
my $prout = $newssh->exec($commands);
print " $prout\n";
}
1;
package Main;
my $connection=RunRemote->new(Password => "YOUR_PASSWORD");
my $response=$connection->DeviceVersion(("uname -a", "ls"));
Hi Skrynesaver,
Thanks so much, that worked like a charm...