Net::OpenSSH(3pm) User Contributed Perl Documentation Net::OpenSSH(3pm)
NAME
Net::OpenSSH - Perl SSH client package implemented on top of OpenSSH
SYNOPSIS
use Net::OpenSSH;
my $ssh = Net::OpenSSH->new($host);
$ssh->error and
die "Couldn't establish SSH connection: ". $ssh->error;
$ssh->system("ls /tmp") or
die "remote command failed: " . $ssh->error;
my @ls = $ssh->capture("ls");
$ssh->error and
die "remote ls command failed: " . $ssh->error;
my ($out, $err) = $ssh->capture2("find /root");
$ssh->error and
die "remote find command failed: " . $ssh->error;
my ($rin, $pid) = $ssh->pipe_in("cat >/tmp/foo") or
die "pipe_in method failed: " . $ssh->error;
print $rin, "hello
";
close $rin;
my ($rout, $pid) = $ssh->pipe_out("cat /tmp/foo") or
die "pipe_out method failed: " . $ssh->error;
while (<$rout>) { print }
close $rout;
my ($in, $out ,$pid) = $ssh->open2("foo");
my ($pty, $pid) = $ssh->open2pty("foo");
my ($in, $out, $err, $pid) = $ssh->open3("foo");
my ($pty, $err, $pid) = $ssh->open3pty("login");
my $sftp = $ssh->sftp();
$sftp->error and die "SFTP failed: " . $sftp->error;
DESCRIPTION
Net::OpenSSH is a secure shell client package implemented on top of OpenSSH binary client ("ssh").
Under the hood
This package is implemented around the multiplexing feature found in later versions of OpenSSH. That feature allows reuse of a previous SSH
connection for running new commands (I believe that OpenSSH 4.1 is the first one to provide all the required functionality).
When a new Net::OpenSSH object is created, the OpenSSH "ssh" client is run in master mode, establishing a permanent (actually, for the
lifetime of the object) connection to the server.
Then, every time a new operation is requested a new "ssh" process is started in slave mode, effectively reusing the master SSH connection
to send the request to the remote side.
Net::OpenSSH Vs Net::SSH::.* modules
Why should you use Net::OpenSSH instead of any of the other Perl SSH clients available?
Well, this is my (biased) opinion:
Net::SSH::Perl is not well maintained nowadays (update: a new maintainer has stepped in so this situation could change!!!), requires a
bunch of modules (some of them very difficult to install) to be acceptably efficient and has an API that is limited in some ways.
Net::SSH2 is much better than Net::SSH::Perl, but not completely stable yet. It can be very difficult to install on some specific operative
systems and its API is also limited, in the same way as Net::SSH::Perl.
Using Net::SSH::Expect, in general, is a bad idea. Handling interaction with a shell via Expect in a generic way just can not be reliably
done.
Net::SSH is just a wrapper around any SSH binary commands available on the machine. It can be very slow as they establish a new SSH
connection for every operation performed.
In comparison, Net::OpenSSH is a pure perl module that doesn't have any mandatory dependencies (obviously, besides requiring OpenSSH
binaries).
Net::OpenSSH has a very perlish interface. Most operations are performed in a fashion very similar to that of the Perl builtins and common
modules (i.e. IPC::Open2).
It is also very fast. The overhead introduced by launching a new ssh process for every operation is not appreciable (at least on my Linux
box). The bottleneck is the latency intrinsic to the protocol, so Net::OpenSSH is probably as fast as an SSH client can be.
Being based on OpenSSH is also an advantage: a proved, stable, secure (to paranoic levels), interoperable and well maintained
implementation of the SSH protocol is used.
On the other hand, Net::OpenSSH does not work on Windows, not even under Cygwin.
Net::OpenSSH specifically requires the OpenSSH SSH client (AFAIK, the multiplexing feature is not available from any other SSH client).
However, note that it will interact with any server software, not just servers running OpenSSH "sshd".
For password authentication, IO::Pty has to be installed. Other modules and binaries are also required to implement specific functionality
(for instance Net::SFTP::Foreign, Expect or rsync(1)).
Net::OpenSSH and Net::SSH2 do not support version 1 of the SSH protocol.
API
Optional arguments
Almost all methods in this package accept as first argument an optional reference to a hash containing parameters ("\%opts"). For instance,
these two method calls are equivalent:
my $out1 = $ssh->capture(@cmd);
my $out2 = $ssh->capture({}, @cmd);
Error handling
Most methods return undef (or an empty list) to indicate failure.
The "error" method can always be used to explicitly check for errors. For instance:
my ($output, $errput) = $ssh->capture2({timeout => 1}, "find /");
$ssh->error and die "ssh failed: " . $ssh->error;
Net::OpenSSH methods
These are the methods provided by the package:
Net::OpenSSH->new($host, %opts)
Creates a new SSH master connection
$host can be a hostname or an IP address. It may also contain the name of the user, her password and the TCP port number where the
server is listening:
my $ssh1 = Net::OpenSSH->new('jack@foo.bar.com');
my $ssh2 = Net::OpenSSH->new('jack:secret@foo.bar.com:10022');
my $ssh3 = Net::OpenSSH->new('jsmith@2001:db8::1428:57ab'); # IPv6
IPv6 addresses may optionally be enclosed in brackets:
my $ssh4 = Net::OpenSSH->new('jsmith@[::1]:1022');
This method always succeeds in returning a new object. Error checking has to be performed explicitly afterwards:
my $ssh = Net::OpenSSH->new($host, %opts);
$ssh->error and die "Can't ssh to $host: " . $ssh->error;
If you have problems getting Net::OpenSSH to connect to the remote host read the troubleshooting chapter near the end of this document.
Accepted options:
user => $user_name
Login name
port => $port
TCP port number where the server is running
passwd => $passwd
password => $passwd
User given password for authentication.
Note that using password authentication in automated scripts is a very bad idea. When possible, you should use public key
authentication instead.
passphrase => $passphrase
Uses given passphrase to open private key.
key_path => $private_key_path
Uses the key stored on the given file path for authentication.
gateway => $gateway
If the given argument is a gateway object as returned by "find_gateway" in Net::OpenSSH::Gateway method, use it to connect to the
remote host.
If it is a hash reference, call the "find_gateway" method first.
For instance, the following code fragments are equivalent:
my $gateway = Net::OpenSSH::Gateway->find_gateway(
proxy => 'http://proxy.corporate.com');
$ssh = Net::OpenSSH->new($host, gateway => $gateway);
and
$ssh = Net::OpenSSH->new($host,
gateway => { proxy => 'http://proxy.corporate.com'});
proxy_command => $proxy_command
Use the given command to establish the connection to the remote host (see "ProxyCommand" on ssh_config(5)).
batch_mode => 1
Disables querying the user for password and passphrases.
ctl_dir => $path
Directory where the SSH master control socket will be created.
This directory and its parents must be writable only by the current effective user or root, otherwise the connection will be
aborted to avoid insecure operation.
By default "~/.libnet-openssh-perl" is used.
ssh_cmd => $cmd
Name or full path to OpenSSH "ssh" binary. For instance:
my $ssh = Net::OpenSSH->new($host, ssh_cmd => '/opt/OpenSSH/bin/ssh');
scp_cmd => $cmd
Name or full path to OpenSSH "scp" binary.
By default it is inferred from the "ssh" one.
rsync_cmd => $cmd
Name or full path to "rsync" binary. Defaults to "rsync".
timeout => $timeout
Maximum acceptable time that can elapse without network traffic or any other event happening on methods that are not immediate (for
instance, when establishing the master SSH connection or inside methods "capture", "system", "scp_get", etc.).
See also "Timeouts".
kill_ssh_on_timeout => 1
This option tells Net::OpenSSH to kill the local slave SSH process when some operation times out.
See also "Timeouts".
strict_mode => 0
By default, the connection will be aborted if the path to the socket used for multiplexing is found to be non-secure (for instance,
when any of the parent directories is writable by other users).
This option can be used to disable that feature. Use with care!!!
async => 1
By default, the constructor waits until the multiplexing socket is available. That option can be used to defer the waiting until
the socket is actually used.
For instance, the following code connects to several remote machines in parallel:
my (%ssh, %ls);
# multiple connections are stablished in parallel:
for my $host (@hosts) {
$ssh{$host} = Net::OpenSSH->new($host, async => 1);
}
# then to run some command in all the hosts (sequentially):
for my $host (@hosts) {
$ssh{$host}->system('ls /');
}
master_opts => [...]
Additional options to pass to the "ssh" command when establishing the master connection. For instance:
my $ssh = Net::OpenSSH->new($host,
master_opts => [-o => "ProxyCommand corkscrew httpproxy 8080 $host"]);
default_ssh_opts => [...]
Default slave SSH command line options for "open_ex" and derived methods.
For instance:
my $ssh = Net::OpenSSH->new($host,
default_ssh_options => [-o => "ConnectionAttempts=0"]);
default_stdin_fh => $fh
default_stdout_fh => $fh
default_stderr_fh => $fh
Default I/O streams for "open_ex" and derived methods (currently, that means any method but "pipe_in" and "pipe_out" and I plan to
remove those exceptions soon!).
For instance:
open my $stderr_fh, '>>', '/tmp/$host.err' or die ...;
open my $stdout_fh, '>>', '/tmp/$host.log' or die ...;
my $ssh = Net::OpenSSH->new($host, default_stderr_fh => $stderr_fh,
default_stdout_fh => $stdout_fh);
$ssh->error and die "SSH connection failed: " . $ssh->error;
$ssh->scp_put("/foo/bar*", "/tmp")
or die "scp failed: " . $ssh->error;
default_stdin_file = $fn
default_stdout_file = $fn
default_stderr_file = $fn
Opens the given filenames and use it as the defaults.
master_stdout_fh => $fh
master_stderr_fh => $fh
Redirect corresponding stdio streams of the master SSH process to given filehandles.
master_stdout_discard => $bool
master_stderr_discard => $bool
Discard corresponding stdio streams.
expand_vars => $bool
Activates variable expansion inside command arguments and file paths.
See "Variable expansion" below.
vars => \%vars
Initial set of variables.
external_master => 1
Instead of launching a new OpenSSH client in master mode, the module tries to reuse an already existent one. "ctl_path" must also
be passed when this option is set. See also "get_ctl_path".
Example:
$ssh = Net::OpenSSH->new('foo', external_master => 1, ctl_path = $path);
default_encoding => $encoding
default_stream_encoding => $encoding
default_argument_encoding => $encoding
Set default encodings. See "Data encoding".
login_handler => &custom_login_handler
Some remote SSH server may require a custom login/authentication interaction not natively supported by Net::OpenSSH. In that cases,
you can use this option to replace the default login logic.
The callback will be invoked repeatly as "custom_login_handler($ssh, $pty, $data)" where $ssh is the current Net::OpenSSH object,
"pty" a IO::Pty object attached to the slave "ssh" process tty and $data a reference to an scalar you can use at will.
The login handler must return 1 after the login process has completed successfully or 0 in case it still needs to do something
else. If some error happens, it must die.
Note, that blocking operations should not be performed inside the login handler (at least if you want the "async" and "timeout"
features to work).
See also the sample script "login_handler.pl" in the "samples" directory.
Usage of this option is incompatible with the "password" and "passphrase" options, you will have to handle password or passphrases
from the custom handler yourself.
$ssh->error
Returns the error condition for the last performed operation.
The returned value is a dualvar as $! (see "$!" in perlvar) that renders an informative message when used in string context or an error
number in numeric context (error codes appear in Net::OpenSSH::Constants).
$ssh->get_user
$ssh->get_host
$ssh->get_port
Return the corresponding SSH login parameters.
$ssh->get_ctl_path
Returns the path to the socket where the OpenSSH master process listens for new multiplexed connections.
($in, $out, $err, $pid) = $ssh->open_ex(\%opts, @cmd)
Note: this is a low level method that, probably, you don't need to use!
That method starts the command @cmd on the remote machine creating new pipes for the IO channels as specified on the %opts hash.
If @cmd is omitted, the remote user shell is run.
Returns four values, the first three ($in, $out and $err) correspond to the local side of the pipes created (they can be undef) and the
fourth ($pid) to the PID of the new SSH slave process. An empty list is returned on failure.
Note that "waitpid" has to be used afterwards to reap the slave SSH process.
Accepted options:
stdin_pipe => 1
Creates a new pipe and connects the reading side to the stdin stream of the remote process. The writing side is returned as the
first value ($in).
stdin_pty => 1
Similar to "stdin_pipe", but instead of a regular pipe it uses a pseudo-tty (pty).
Note that on some OSs (i.e. HP-UX, AIX), ttys are not reliable. They can overflow when large chunks are written or when data is
written faster than it is read.
stdin_fh => $fh
Duplicates $fh and uses it as the stdin stream of the remote process.
stdin_file => $filename
stdin_file => @open_args
Opens the file of the given name for reading and uses it as the remote process stdin stream.
If an array reference is passed its contents are used as the arguments for the underlying open call. For instance:
$ssh->system({stdin_file => ['-|', 'gzip -c -d file.gz']}, $rcmd);
stdin_discard => 1
Uses /dev/null as the remote process stdin stream.
stdout_pipe => 1
Creates a new pipe and connects the writing side to the stdout stream of the remote process. The reading side is returned as the
second value ($out).
stdout_pty => 1
Connects the stdout stream of the remote process to the pseudo-pty. This option requires "stdin_pty" to be also set.
stdout_fh => $fh
Duplicates $fh and uses it as the stdout stream of the remote process.
stdout_file => $filename
stdout_file => @open_args
Opens the file of the given filename and redirect stdout there.
stdout_discard => 1
Uses /dev/null as the remote process stdout stream.
stdinout_socket => 1
Creates a new socketpair, attachs the stdin an stdout streams of the slave SSH process to one end and returns the other as the
first value ($in) and undef for the second ($out).
Example:
my ($socket, undef, undef, $pid) = $ssh->open_ex({stdinout_socket => 1},
'/bin/netcat $dest');
See also "open2socket".
stdinout_dpipe => $cmd
stdinout_dpipe => @cmd
Runs the given command locally attaching its stdio streams to those of the remote SSH command. Conceptually it is equivalent to the
dpipe(1) shell command.
stderr_pipe => 1
Creates a new pipe and connects the writing side to the stderr stream of the remote process. The reading side is returned as the
third value ($err).
Example:
my $pid = $ssh->open_ex({stdinout_dpipe => 'vncviewer -stdio'},
x11vnc => '-inetd');
stderr_fh => $fh
Duplicates $fh and uses it as the stderr stream of the remote process.
stderr_file => $filename
Opens the file of the given name and redirects stderr there.
stderr_to_stdout => 1
Makes stderr point to stdout.
tty => $bool
Tells ssh to allocate a pseudo-tty for the remote process. By default, a tty is allocated if remote command stdin stream is
attached to a tty.
When this flag is set and stdin is not attached to a tty, the ssh master and slave processes may generate spurious warnings about
failed tty operations. This is caused by a bug present in older versions of OpenSSH.
close_slave_pty => 0
When a pseudo pty is used for the stdin stream, the slave side is automatically closed on the parent process after forking the ssh
command.
This option dissables that feature, so that the slave pty can be accessed on the parent process as "$pty->slave". It will have to
be explicitly closed (see IO::Pty)
quote_args => $bool
See "Shell quoting" below.
ssh_opts => @opts
List of extra options for the "ssh" command.
This feature should be used with care, as the given options are not checked in any way by the module, and they could interfere with
it.
tunnel => $bool
Instead of executing a command in the remote host, this option instruct Net::OpenSSH to create a TCP tunnel. The arguments become
the target IP and port.
Example:
my ($in, $out, undef, $pid) = $ssh->open_ex({tunnel => 1}, $IP, $port);
See also "Tunnels".
encoding => $encoding
argument_encoding => $encoding
Set encodings. See "Data encoding".
Usage example:
# similar to IPC::Open2 open2 function:
my ($in_pipe, $out_pipe, undef, $pid) =
$ssh->open_ex( { stdin_pipe => 1,
stdout_pipe => 1 },
@cmd )
or die "open_ex failed: " . $ssh->error;
# do some IO through $in/$out
# ...
waitpid($pid);
$ssh->system(\%opts, @cmd)
Runs the command @cmd on the remote machine.
Returns true on sucess, undef otherwise.
The error status is set to "OSSH_SLAVE_CMD_FAILED" when the remote command exits with a non zero code (the code is available from $?,
see "$?" in perlvar).
Example:
$ssh->system('ls -R /')
or die "ls failed: " . $ssh->error";
As for "system" builtin, "SIGINT" and "SIGQUIT" signals are blocked. (see "system" in perlfunc). Also, setting $SIG{CHLD} to "IGNORE"
or to a custom signal handler will interfere with this method.
Accepted options:
stdin_data => $input
stdin_data => @input
Sends the given data through the stdin stream to the remote process.
For example, the following code creates a file on the remote side:
$ssh->system({stdin_data => @data}, "cat >/tmp/foo")
or die "unable to write file: " . $ssh->error;
timeout => $timeout
The operation is aborted after $timeout seconds elapsed without network activity.
See also "Timeouts".
async => 1
Does not wait for the child process to exit. The PID of the new process is returned.
Note that when this option is combined with "stdin_data", the given data will be transferred to the remote side before returning
control to the caller.
See also the "spawn" method documentation below.
stdin_fh => $fh
stdin_discard => $bool
stdout_fh => $fh
stdout_discard => $bool
stderr_fh => $fh
stderr_discard => $bool
stderr_to_stdout => $bool
stdinout_dpipe => $cmd
tty => $bool
See the "open_ex" method documentation for an explanation of these options.
$ok = $ssh->test(\%opts, @cmd);
Runs the given command and returns its success/failure exit status as 1 or 0 respectively. Returns undef when something goes wrong in
the SSH layer.
Error status is not set to OSSH_SLAVE_CMD_FAILED when the remote command exits with a non-zero code.
By default this method discards the remote command "stdout" and "sterr" streams.
Usage example:
if ($ssh->test(ps => -C => $executable)) {
say "$executable is running on remote machine"
}
else {
die "something got wrong: ". $ssh->error if $ssh->error;
say "$executable is not running on remote machine"
}
This method support the same set of options as "system", except "async" and "tunnel".
$output = $ssh->capture(\%opts, @cmd);
@output = $ssh->capture(\%opts, @cmd);
This method is conceptually equivalent to the perl backquote operator (i.e. "`ls`"): it runs the command on the remote machine and
captures its output.
In scalar context returns the output as a scalar. In list context returns the output broken into lines (it honors $/, see "$/" in
perlvar).
When an error happens while capturing (for instance, the operation times out), the partial captured output will be returned. Error
conditions have to be explicitly checked using the "error" method. For instance:
my $output = $ssh->capture({ timeout => 10 },
"echo hello; sleep 20; echo bye");
$ssh->error and
warn "operation didn't complete successfully: ". $ssh->error;
print $output;
Setting $SIG{CHLD} to a custom signal handler or to "IGNORE" will interfere with this method.
Accepted options:
stdin_data => $input
stdin_data => @input
timeout => $timeout
See "Timeouts".
stdin_fh => $fh
stdin_discard => $bool
stderr_fh => $fh
stderr_discard => $bool
stderr_to_stdout => $bool
tty => $bool
See the "open_ex" method documentation for an explanation of these options.
($output, $errput) = $ssh->capture2(\%opts, @cmd)
captures the output sent to both stdout and stderr by @cmd on the remote machine.
Setting $SIG{CHLD} to a custom signal handler or to "IGNORE" will also interfere with this method.
The accepted options are:
stdin_data => $input
stdin_data => @input
See the "system" method documentation for an explanation of these options.
timeout => $timeout
See "Timeouts".
stdin_fh => $fh
stdin_discard => $bool
tty => $bool
See the "open_ex" method documentation for an explanation of these options.
($in, $pid) = $ssh->pipe_in(\%opts, @cmd)
This method is similar to the following Perl "open" call
$pid = open $in, '|-', @cmd
but running @cmd on the remote machine (see "open" in perlfunc).
No options are currently accepted.
There is no need to perform a waitpid on the returned PID as it will be done automatically by perl when $in is closed.
Example:
my ($in, $pid) = $ssh->pipe_in('cat >/tmp/fpp')
or die "pipe_in failed: " . $ssh->error;
print $in $_ for @data;
close $in or die "close failed";
($out, $pid) = $ssh->pipe_out(\%opts, @cmd)
Reciprocal to previous method, it is equivalent to
$pid = open $out, '-|', @cmd
running @cmd on the remote machine.
No options are currently accepted.
($in, $out, $pid) = $ssh->open2(\%opts, @cmd)
($pty, $pid) = $ssh->open2pty(\%opts, @cmd)
($socket, $pid) = $ssh->open2socket(\%opts, @cmd)
($in, $out, $err, $pid) = $ssh->open3(\%opts, @cmd)
($pty, $err, $pid) = $ssh->open3pty(\%opts, @cmd)
Shortcuts around "open_ex" method.
$pid = $ssh->spawn(\%opts, @_)
Another "open_ex" shortcut, it launches a new remote process in the background and returns the PID of the local slave SSH process.
At some later point in your script, "waitpid" should be called on the returned PID in order to reap the slave SSH process.
For instance, you can run some command on several hosts in parallel with the following code:
my %conn = map { $_ => Net::OpenSSH->new($_, async => 1) } @hosts;
my @pid;
for my $host (@hosts) {
open my($fh), '>', "/tmp/out-$host.txt"
or die "unable to create file: $!";
push @pid, $conn{$host}->spawn({stdout_fh => $fh}, $cmd);
}
waitpid($_, 0) for @pid;
Note that "spawn" shouldn't be used to start detached remote processes that may survive the local program (see also the "FAQ" about
running remote processes detached).
($socket, $pid) = $ssh->open_tunnel(\%opts, $dest_host, $port)
Similar to "open2socket", but instead of running a command, it opens a TCP tunnel to the given address. See also "Tunnels".
$out = $ssh->capture_tunnel(\%opts, $dest_host, $port)
@out = $ssh->capture_tunnel(\%opts, $dest_host, $port)
Similar to "capture", but instead of running a command, it opens a TCP tunnel.
Example:
$out = $ssh->capture_tunnel({stdin_data => join("
",
"GET / HTTP/1.0",
"Host: www.perl.org",
"", "") },
'www.perl.org', 80)
See also "Tunnels".
$ssh->scp_get(\%opts, $remote1, $remote2,..., $local_dir_or_file)
$ssh->scp_put(\%opts, $local, $local2,..., $remote_dir_or_file)
These two methods are wrappers around the "scp" command that allow transfers of files to/from the remote host using the existing SSH
master connection.
When transferring several files, the target argument must point to an existing directory. If only one file is to be transferred, the
target argument can be a directory or a file name or can be ommited. For instance:
$ssh->scp_get({glob => 1}, '/var/tmp/foo*', '/var/tmp/bar*', '/tmp');
$ssh->scp_put('/etc/passwd');
Both "scp_get" and "scp_put" methods return a true value when all the files are transferred correctly, otherwise they return undef.
Accepted options:
quiet => 0
By default, "scp" is called with the quiet flag "-q" enabled in order to suppress progress information. This option allows
reenabling the progress indication bar.
verbose => 1
Calls "scp" with the "-v" flag.
recursive => 1
Copy files and directories recursively.
glob => 1
Allow expansion of shell metacharacters in the sources list so that wildcards can be used to select files.
glob_flags => $flags
Second argument passed to File::Glob::bsd_glob function. Only available for "scp_put" method.
copy_attrs => 1
Copies modification and access times and modes from the original files.
bwlimit => $Kbits
Limits the used bandwith, specified in Kbit/s.
timeout => $secs
The transfer is aborted if the connection does not finish before the given timeout elapses. See also "Timeouts".
async => 1
Doesn't wait for the "scp" command to finish. When this option is used, the method returns the PID of the child "scp" process.
For instance, it is possible to transfer files to several hosts in parallel as follows:
use Errno;
my (%pid, %ssh);
for my $host (@hosts) {
$ssh{$host} = Net::OpenSSH->new($host, async => 1);
}
for my $host (@hosts) {
$pid{$host} = $ssh{$host}->scp_put({async => 1}, $local_fn, $remote_fn)
or warn "scp_put to $host failed: " . $ssh{$host}->error . "
";
}
for my $host (@hosts) {
if (my $pid = $pid{$host}) {
if (waitpid($pid, 0) > 0) {
my $exit = ($? >> 8);
$exit and warn "transfer of file to $host failed ($exit)
";
}
else {
redo if ($! == EINTR);
warn "waitpid($pid) failed: $!
";
}
}
}
stdout_fh => $fh
stderr_fh => $fh
stderr_to_stdout => 1
These options are passed unchanged to method "open_ex", allowing capture of the output of the "scp" program.
Note that "scp" will not generate progress reports unless its stdout stream is attached to a tty.
$ssh->rsync_get(\%opts, $remote1, $remote2,..., $local_dir_or_file)
$ssh->rsync_put(\%opts, $local1, $local2,..., $remote_dir_or_file)
These methods use "rsync" over SSH to transfer files from/to the remote machine.
They accept the same set of options as the SCP ones.
Any unrecognized option will be passed as an argument to the "rsync" command (see rsync(1)). Underscores can be used instead of dashes
in "rsync" option names.
For instance:
$ssh->rsync_get({exclude => '*~',
verbose => 1,
safe_links => 1},
'/remote/dir', '/local/dir');
$sftp = $ssh->sftp(%sftp_opts)
Creates a new Net::SFTP::Foreign object for SFTP interaction that runs through the ssh master connection.
@call = $ssh->make_remote_command(%opts, @cmd)
$call = $ssh->make_remote_command(\%opts, @cmd)
This method returns the arguments required to execute a command on the remote machine via SSH. For instance:
my @call = $ssh->make_remote_command(ls => "/var/log");
system @call;
In scalar context, returns the arguments quoted and joined into one string:
my $remote = $ssh->make_remote_comand("cd /tmp/ && tar xf -");
system "tar cf - . | $remote";
$ssh->wait_for_master($async)
When the connection has been established by calling the constructor with the "async" option, this call allows one to advance the
process.
If $async is true, it will perform any work that can be done inmediately without waiting (for instance, entering the password or
checking for the existence of the multiplexing socket) and then return. If a false value is given, it will finalize the connection
process and wait until the multiplexing socket is available.
It returns a true value after the connection has been successfully established. False is returned if the connection process fails or if
it has not yet completed (then, the "error" method can be used to distinguish between both cases).
$ssh->check_master
This method runs several checks to ensure that the master connection is still alive.
$ssh->shell_quote(@args)
Returns the list of arguments quoted so that they will be restored to their original form when parsed by the remote shell.
In scalar context returns the list of arguments quoted and joined.
Usually this task is done automatically by the module. See "Shell quoting" below.
This method can also be used as a class method.
Example:
my $quoted_args = Net::OpenSSH->shell_quote(@args);
system('ssh', '--', $host, $quoted_args);
$ssh->shell_quote_glob(@args)
This method is like the previous "shell_quote" but leaves wildcard characters unquoted.
It can be used as a class method also.
$ssh->set_expand_vars($bool)
Enables/disables variable expansion feature (see "Variable expansion").
$ssh->get_expand_vars
Returns current state of variable expansion feature.
$ssh->set_var($name, $value)
$ssh->get_var($name, $value)
These methods allow to change and to retrieve the value of the logical value of the given name.
$ssh->get_master_pid
Returns the PID of the master SSH process
$ssh->master_exited
This methods allows one to tell the module that the master process has exited when we get its PID from some external wait or waitpid
call. For instance:
my $ssh = Net::OpenSSH->new('foo', async => 1);
# create new processes
# ...
# rip them...
my $master_pid = $ssh->master_pid;
while ((my $pid = wait) > 0) {
if ($pid == $master_pid) {
$ssh->master_exited;
}
}
If your program rips the master process and this method is not called, the OS could reassign the PID to a new unrelated process and the
module would try to kill it at object destruction time.
Shell quoting
By default, when invoking remote commands, this module tries to mimic perl "system" builtin in regard to argument processing. Quoting
"system" in perlfunc:
Argument processing varies depending on the number of arguments. If
there is more than one argument in LIST, or if LIST is an array with
more than one value, starts the program given by the first element
of the list with arguments given by the rest of the list. If there
is only one scalar argument, the argument is checked for shell
metacharacters, and if there are any, the entire argument is passed
to the system's command shell for parsing (this is "/bin/sh -c" on
Unix platforms, but varies on other platforms).
Take for example Net::OpenSSH "system" method:
$ssh->system("ls -l *");
$ssh->system('ls', '-l', '/');
The first call passes the argument unchanged to ssh and it is executed in the remote side through the shell which interprets
metacharacters.
The second call escapes any shell metacharacters so that, effectively, it is equivalent to calling the command directly and not through the
shell.
Under the hood, as the Secure Shell protocol does not provide for this mode of operation and always spawns a new shell where it runs the
given command, Net::OpenSSH quotes any shell metacharacters in the command list.
All the methods that invoke a remote command (system, open_ex, etc.) accept the option "quote_args" that allows one to force/disable shell
quoting.
For instance:
$ssh->system({quote_args => 1}, "/path with spaces/bin/foo");
will correctly handle the spaces in the program path.
The shell quoting mechanism implements some extensions (for instance, performing redirections to /dev/null on the remote side) that can be
dissabled with the option "quote_args_extended":
$ssh->system({ stderr_discard => 1,
quote_args => 1, quote_args_extended => 0 },
@cmd);
The option "quote_args" can also be used to disable quoting when more than one argument is passed. For instance, to get some pattern
expanded by the remote shell:
$ssh->system({quote_args => 0}, 'ls', '-l', "/tmp/files_*.dat");
The method "shell_quote" can be used to selectively quote some arguments and leave others untouched:
$ssh->system({quote_args => 0},
$ssh->shell_quote('ls', '-l'),
"/tmp/files_*.dat");
When the glob option is set in scp and rsync file transfer methods, an alternative quoting method that knows about file wildcards and
passes them unquoted is used. The set of wildcards recognized currently is the one supported by bash(1).
Another way to selectively use quote globing or fully disable quoting for some specific arguments is to pass them as scalar references or
double scalar references respectively. In practice, that means prepending them with one or two backslashes. For instance:
# quote the last argument for globing:
$ssh->system('ls', '-l', '/tmp/my files/filed_*dat');
# append a redirection to the remote command
$ssh->system('ls', '-lR', \'>/tmp/ls-lR.txt');
# expand remote shell variables and glob in the same command:
$ssh->system('tar', 'czf', \'$HOME/out.tgz', '/var/log/server.*.log');
As shell quoting is a tricky matter, I expect bugs to appear in this area. You can see how "ssh" is called, and the quoting used setting
the following debug flag:
$Net::OpenSSH::debug |= 16;
Also, the current shell quoting implementation expects a shell compatible with Unix "sh" in the remote side. It will not work as expected
if for instance, the remote machine runs Windows, VMS or it is a router.
As a workaround, do any required quoting yourself and pass the quoted command as a string so that no further quoting is performed. For
instance:
# for VMS
$ssh->system('DIR/SIZE NFOO::USERS:[JSMITH.DOCS]*.TXT;0');
I plan to add support for different quoting mechanisms in the future... if you need it now, just ask for it!!!
The current quoting mechanism does not handle possible aliases defined by the remote shell. In that case, to force execution of the command
instead of the alias, the full path to the command must be used.
Timeouts
In order to stop remote processes when they timeout, the ideal aproach would be to send them signals through the SSH connection as
specified by the protocol standard.
Unfortunately OpenSSH does not implement that feature so Net::OpenSSH has to use other imperfect approaches:
o close slave I/O streams
Closing the STDIN and STDOUT streams of the unresponsive remote process will effectively deliver a SIGPIPE when it tries to access any
of them.
Remote processes may not access STDIN or STDOUT and even them, Net::OpenSSH can only close these channels when it is capturing them, so
this approach does not always work.
o killing the local SSH slave process
This action may leave the remote process running, creating a remote orphan so Net::OpenSSH does not use it unless the construction
option "kill_ssh_on_timeout" is set.
Luckily, future versions of OpenSSH will support signaling remote processes via the mux channel.
Variable expansion
The variable expansion feature allows one to define variables that are expanded automatically inside command arguments and file paths.
This feature is disabled by default. It is intended to be used with Net::OpenSSH::Parallel and other similar modules.
Variables are delimited by a pair of percent signs ("%"), for instance "%HOST%". Also, two consecutive percent signs are replaced by a
single one.
The special variables "HOST", "USER" and "PORT" are maintained internally by the module and take the obvious values.
Variable expansion is performed before shell quoting (see "Shell quoting").
Some usage example:
my $ssh = Net::OpenSSH->new('server.foo.com', expand_vars => 1);
$ssh->set_var(ID => 42);
$ssh->system("ls >/tmp/ls.out-%HOST%-%ID%");
will redirect the output of the "ls" command to "/tmp/ls.out-server.foo.com-42" on the remote host.
Tunnels
Besides running commands on the remote host, Net::OpenSSH also allows to tunnel TCP connections to remote machines reachable from the SSH
server.
That feature is made available through the "tunnel" option of the "open_ex" method, and also through wrapper methods "open_tunnel" and
"capture_tunnel" and most others where it makes sense.
Example:
$ssh->system({tunnel => 1,
stdin_data => "GET / HTTP/1.0
",
stdout_file => "/tmp/$server.res"},
$server, 80)
or die "unable to retrieve page: " . $ssh->error;
or capturing the output of several requests in parallel:
my @pids;
for (@servers) {
my $pid = $ssh->spawn({tunnel => 1,
stdin_file => "/tmp/request.req",
stdout_file => "/tmp/$_.res"},
$_, 80);
if ($pid) {
push @pids, $pid;
}
else {
warn "unable to spawn tunnel process to $_: " . $ssh->error;
}
}
waitpid ($_, 0) for (@pids);
Under the hood, in order to create a tunnel, a new "ssh" process is spawned with the option "-W${address}:${port}" (available from OpenSSH
5.4 and upwards) making it redirect its stdio streams to the remote given address. Unlike when "ssh" "-L" options is used to create
tunnels, no TCP port is opened on the local machine at any time so this is a perfectly secure operation.
The PID of the new process is returned by the named methods. It must be reaped once the pipe or socket handlers for the local side of the
tunnel have been closed.
OpenSSH 5.4 or later is required for the tunnels functionality to work. Also, note that tunnel forwarding may be administratively forbidden
at the server side (see sshd(8) and sshd_config(5) or the documentation provided by your SSH server vendor).
Data encoding
Net::OpenSSH has some support for transparently converting the data send or received from the remote server to Perl internal unicode
representation.
The methods supporting that feature are those that move data from/to Perl data structures (i.e. "capture", "capture2", "capture_tunnel" and
methods supporting the "stdin_data" option). Data accessed through pipes, sockets or redirections is not affected by the encoding options.
It is also possible to set the encoding of the command and arguments passed to the remote server on the command line.
By default, if no encoding option is given on the constructor or on the method calls, Net::OpenSSH will not perform any encoding
transformation, effectively processing the data as latin1.
When data can not be converted between the Perl internal representation and the selected encoding inside some Net::OpenSSH method, it will
fail with an "OSSH_ENCODING_ERROR" error.
The supported encoding options are as follows:
stream_encoding => $encoding
sets the encoding of the data send and received on capture methods.
argument_encoding => $encoding
sets the encoding of the command line arguments
encoding => $encoding
sets both "argument_encoding" and "stream_encoding".
The constructor also accepts "default_encoding", "default_stream_encoding" and "default_argument_encoding" that set the defaults.
Diverting "new"
When a code ref is installed at $Net::OpenSSH::FACTORY, calls to new will be diverted through it.
That feature can be used to transparently implement connection caching, for instance:
my $old_factory = $Net::OpenSSH::FACTORY;
my %cache;
sub factory {
my ($class, %opts) = @_;
my $signature = join("