Subject: | problem passing net:ssh2 object to another function |
I've divided my program in 3 subs, ssh_connect,ssh_exec,ssh_disconnect.
I create my ssh2 object in the connect sub, and if the connection is
sucessfull i return it.
Then in the main program i pass ssh2 object to the exec and disconnect sub.
Then i run ssh_exec($ssh,"ls -l") it simply doesn't do anything, not
even an error.
I'm i doing anyting wrong or is this a bug?
Heres my code:
use Net::SSH2;
use Net::SSH2::Channel;
sub ssh_connect{
my $ip=$_[0];
my $myuser=$_[1];
my $mypass=$_[2];
my $ssh2 = Net::SSH2->new();
$ssh2->poll(1);
$ssh2->connect($ip);
$login = $ssh2->auth_password($myuser, $mypass);
if ($login){
return $ssh2;
}
else{
return 0;
}
}
sub ssh_exec{
my $ssh2=$_[0];
my $cmd=$_[1];
$chan = $ssh2->channel();
$chan->blocking(0);
$chan->exec($cmd);
my $poll = { handle => $chan, events => -1 };
while ($ssh2->poll(500, [ $poll ])) {
if ($poll->{revents}{out}) {
#print "Out event is set\n";
while (<$chan>) {
$r=$r.$_;
}
}
if ($poll->{revents}{channel_closed} ||
$poll->{revents}{listener_closed}) {
my $exit = $chan->exit_status();
return $r;
}
}
print "Timeout occurred while executing (".$cmd.").\n";
return 0;
}
sub ssh_disconnect{
my $ssh2=$_[0];
$ssh2->disconnect();
}
my $ssh = ssh_connect("127.0.0.1","user","password");
if ($ssh == 0){
print "Connection failed.\n";
exit;
}
$r = ssh_exec($ssh,"ls-l");
print $r;
ssh_disconnect($ssh);
print "Finished.\n";
exit;