hanish
hanish

Reputation: 123

How can I execute a series of commands using the Net::SSH::Any module?

I want to execute multiple commands in the same session after connecting to a server with 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 expected the following output:

/usr/script

but instead I am getting:

/home/user

How can I execute multiple commands in a single session?

Upvotes: 4

Views: 685

Answers (1)

ThisSuitIsBlackNot
ThisSuitIsBlackNot

Reputation: 24073

You'll have to chain your commands in the remote shell like this:

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

You have to do it this way because even though both currently-supported backends to Net::SSH::Any provide other ways to do this (Net::OpenSSH has open2pty and Net::SSH2 has channels), the Net::SSH::Any API doesn't expose these.

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

Upvotes: 3

Related Questions