[Perl] [net :: ssh2] How to save an ssh connection when executing a remote command

I am working on a perl script using net :: ssh2 to make an SSH connection to a remote server. (I work on windows)

I chose Net :: SSH2 because I had to make some SFTP connections in the same script.

So far my sftp connections are working fine. The problem is that I am trying to execute the "long-duration" command. I mean a command that can take more than 30 seconds to complete.

$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 will be successful, the file will be sent correctly, but the execution will not be completed (completely). I mean, I think that the command is sent for execution, but immediately completed or not sent at all, I'm not sure.

I want the script to wait for the command to complete before disabling everything (just because sometimes I need to get the result of the command)

Does anyone know how to solve this? :( The cpan documentation is not very explicit for this

Thanks!

PS: I am open to any comments or suggestions :)

Edit: after some test, I can say that the command is sent, but aborted. My test was to run another perl script on a remote server. This script is written to a flat file. In this test, the script is run, the file is half full. I mean, the file is brutally stopped in the middle.

On the other hand, when I executed "sleep (10)" right after "$ channel-> exec ()", the script exits successfully. The problem is that I cannot write "sleep (10)" (I do not know if it will take 9 or 11 seconds (or more, you will see my point)

+4
source share
1 answer

Instead, you can use Net :: SSH :: Any .

It provides a higher level and simplifies the use of the API and can use Net :: SSH2 or Net :: OpenSSH to handle an 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. 

Please note that SFTP support (via Net :: SFTP :: Foreign) has been added to version 0.03, which I just uploaded to CPAN.

+2
source

Source: https://habr.com/ru/post/1447000/


All Articles