[Perl][net::ssh2] How to keep the ssh connection while executing remote command
perl
Solution
You can try using Net::SSH::Any instead.
It provides a higher level and easier to use API and can use Net::SSH2 or Net::OpenSSH to handle the SSH connection.
For instance:
use Net::SSH::Any;
my $ssh = Net::SSH::Any->new($host, user => $user, password => $password);
$ssh->error and die $ssh->error;
my $sftp = $ssh->sftp;
$sftp->put('local_path', 'remote_path');
my $output = $ssh->capture($cmd);
print "command $cmd output:\n$output\n\n";
$sftp->put('local_path1', 'remote_path1');
# no need to explicitly disconnect, connections will be closed when
# both $sftp and $ssh go out of scope.
Note that SFTP support (via Net::SFTP::Foreign) has been added on version 0.03 that I have just uploaded to CPAN.
Problem
I'm working on a perl script using net::ssh2 to make a SSH connection to a remote server. (I'm working on windows) I chose Net::SSH2 because i had to make some SFTP connections in the same script. For now, my sftp connections work perfectly. The problem is when i try to execute a "long-duration" command. I mean a command which execution can take more than 30sec. ``` $ssh2 = Net::SSH2->new(); $ssh2->connect('HOST') or die; if($ssh2->auth(username=>'USER', password=>'PSWD')) { $sftp = Net::SFTP::Foreign->new(ssh2=>$ssh2, backend=>'Net_SSH2'); $sftp->put('local_path', 'remote_path'); $channel=$ssh2->channel(); ## $channel->shell('BCP_COMMAND_OR_OTHER_PERL_SCRIPT'); # OR (I tried both, both failed :( ) $channel->exec('BCP_COMMAND_OR_OTHER_PERL_SCRIPT'); ## $channel->wait_closed(); $channel->close(); print "End of command"; $sftp_disconnect(); } $ssh2->disconnect(); ``` When i execute this script, the connection is successfull, the file is correctly sent but the execution is not (completely) performed. I mean, I think the command is sent for execution but terminated immediatly or not sent at all, i'm not sure. What i want is the script waits until the command is completly finished before disconnect everything (just because sometimes, i need to get the result of the command execution) Does anyone know how to solve this? :( The cpan documentation is not very explicit for this Thanks! PS: I'm open to any remarks or suggestion :) Edit: After some test, i can say that the command is sent but is interrupted. My test was to start another perl script on the remote server. This script writes in a flat file. In this test, the script is started, the file is half-filled. I mean, the file is brutaly stopped in the middle. In the other hand, when i performed a "sleep(10)" just after the "$channel->exec()", the script goes to the end successfully. Problem is, that I can't write a "sleep(10)" (i don't know if it will take 9 or 11 seconds (or more, you see my point)