How to execute a number of commands using the Net :: SSH :: Any module?

I want to execute several commands in the same session after connecting to the server using Net :: SSH :: Any.

My sample code is as follows:

use strict; use warnings; use Net::SSH::Any; my $host = "ip address"; my $user = "user"; my $passwd = "pass"; my $cmd1 = 'cd /usr/script'; my $ssh = Net::SSH::Any->new($host, user => $user, password => $passwd); $ssh->system($cmd1); my $pwd = $ssh->capture("pwd"); print $pwd; 

I was expecting the following output:

 /usr/script 

but instead I get:

 /home/user 

How can I execute several commands in one session?

+4
source share
1 answer

You need to bind your commands in a remote shell as follows:

 my $cwd = $ssh->capture( q{cd /usr/script && pwd} ); 

You should do it this way because although both of the currently supported backends in Net :: SSH :: Any provide other ways to do this (Net :: OpenSSH has open2pty and Net :: SSH2 has channels ), Net :: SSH :: Any API do not expose them.

For example, system calls the Net :: OpenSSH system method or creates Net :: SSH2 :: Channel and calls process('exec' => $cmd) (limited to one command per channel).

+3
source

All Articles