4

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?

1 Answer 1

3

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).

Sign up to request clarification or add additional context in comments.

1 Comment

The development version from GitHub already supports that via the pipe method. It should be considered an experimental feature yet though. Another option is to use the stdin_data option when calling capture or any other method. For instance: $ssh->capture({stdin_data => join("\n", @cmds, "")})

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.