The Perl Toolchain Summit needs more sponsors. If your company depends on Perl, please support this very important event.

NAME

Net::OpenSSH - Perl SSH client package implemented on top of OpenSSH

SYNOPSIS

  use Net::OpenSSH;

  my $ssh = Net::OpenSSH->new($host);
  $ssh->system("ls /tmp");

  my @ls = $ssh->capture("ls");
  my ($out, $err) = $ssh->capture2("find /root");

  my ($rin, $pid) = $ssh->pipe_in("cat >/tmp/foo");
  print $rin, "hello\n";
  close $rin;

  my ($rout, $pid) = $ssh->pipe_out("cat /tmp/foo");
  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();

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 reusing a previous SSH connection to run 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 stablishing 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 the other several Perl SSH clients available?

Well, that's my (biased) opinion:

Net::SSH::Perl is not well maintained nowadays, 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 operation are performed in a fashion very similar to that or 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 apreciable (at least on my Linux box). The bottleneck is on 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 in several ways as a proved, stable, secure (to paranoic levels), interoperable and well maintained implementation of the SSH protocol is used.

On the other hand, Net::OpenSSH will not run on Windows (well, maybe under the perl that comes with Cygwin... tell me if you try it, please!)

Net::OpenSSH specifically requires OpenSSH SSH client (AFAIK, the multiplexing feature is not available from any other SSH client). Though, note that it will interacturate with any server software, not just servers running OpenSSH sshd.

For password authentication, IO::Pty has to be installed. Other modules are also required to implement specific functionality (for instance Net::SFTP::Foreign or Expect).

API

Several of the methods on this package accept as first argument a reference to a hash containing optional parameters (\%opts) that can be omitted. 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 method error can always be used to check for errors explicitly. For instace:

  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:

  *** Note that this is an early release, the ***
  *** module API has not yet stabilized!!!    ***
Net::OpenSSH->new($host, %opts)

creates a new SSH master connection

$host can be a hostname or and IP address. It can optionally contain also 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');

This method always succeeds 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;

The accepted options are:

user => $user_name

login name

port => $port

TCP port number where the server is running

passwd => $passwd

user password to use when loging on the remote side.

Note that using password authentication in automated scripts is a very bad idea. When possible, you should use public key authentication instead.

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');
timeout => $timeout

maximum acceptable time that can elapse without network traffic or any other event happening on methods that are not inmediate (for instance, when stablishing the master SSH connection or inside capture method).

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);
  for my $host (@hosts) {
      $ssh{$host} = Net::OpenSSH->new($host, async => 1);
  }
  for my $host (@hosts) {
      $ssh{$host}->system('ls /');
  }
}
master_opts => [...]

additional options to pass to the ssh command when stablishing the master connection. For instance:

  my $ssh = Net::OpenSSH->new($host,
      master_opts => [-o => "ProxyCommand corkscrew httpproxy 8080 $host"]);
$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 on string context or an error number on numeric context (error codes appear in Net::OpenSSH::Constants).

$ssh->system(@cmd)

Similar to system builtin, runs the command @cmd on the remote machine using the current stdin, stdout and stderr streams for IO.

Example:

   $ssh->system('ls -R /');

The value returned also follows the system builtin convention (see "$?" in perlvar).

($in, $out, $err, $pid) = $ssh->open_ex(\%opts, @cmd)

That method starts the command @cmd on the remote machine creating new pipes for the IO channels as specified on the %opts hash.

Returns fivefour values, the first three correspond to the local side of the pipes created (they can be undef) and the fourth to the PID of the new SSH slave process.

Note that waitpid has to be used afterwards to reap the slave SSH process.

The method returns an empty list on failure.

The accepted options are:

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.

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), ttys are not reliable. They can be overflowed 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.

stdout_pipe => 1

creates a new pipe and connects the writting side to the stdout stream of the remote process. The reading side is returned as the second value.

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.

stderr_pipe => 1

creates a new pipe and connects the writting side to the stderr stream of the remote process. The reading side is returned as the third value.

stderr_fh => $fh

duplicates $fh and uses it as the stderr stream of the remote process.

stderr_to_stdout => 1

makes stderr point to stdout

tty => $bool

tells the remote process that it is connected to a tty

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

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);
($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).

Currently no options are 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.

Currently no options are accepted.

($in, $out, $pid) = $ssh->open2(\%opts, @cmd)
($pty, $pid) = $ssh->open2pty(\%opts, @cmd)
($in, $out, $err, $pid) = $ssh->open3(\%opts, @cmd)
($pty, $err, $pid) = $ssh->open3pty(\%opts, @cmd)

shortuts around open_ex method.

$output = $ssh->capture(\%opts, @cmd);
@output = $ssh->capture(\%opts, @cmd);

this method is conceptually equivalent to perl backquote operator (i.e. `ls`) running the command on the remote machine and capturing its output.

On scalar context returns the output as an scalar. In list context returns the output broken in 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;

The accepted options are as follows:

stderr_to_stdout => $bool

redirect stderr to stdout. Both streams will be captured on the same scalar interleaved.

stderr_fh => $fh

attachs the remote command stderr stream to the given file handle.

stdin_data => $input
stdin_data => \@input

sends the given data to the stdin stream while simultaneously capturing the output.

stdin_fh => $fh

attachs the remote command stdin stream to the given file handle.

timeout => $timeout

The operation is aborted after $timeout seconds elapse without any network activity.

($output, $errput) = $ssh->capture2(\%opts, @cmd)

captures the output sent to both stdout and stderr by @cmd on the remote machine.

The accepted options are:

stdin_data => $input
stdin_data => @input

sends the given data to the stdin stream while simultaneously captures the output on stdout and stderr.

stdin_fh => $fh

attachs the remote command stdin stream to the given file handle.

timeout => $timeout

The operation is aborted after $timeout seconds elapse without network activity.

$sftp = $ssh->sftp

creates a new Net::SFTP::Foreign object for SFTP interaction that runs through the ssh master connection.

$ssh->wait_for_master($async)

When the connection has been stablished calling the constructor with the async option, this call allows 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) 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 succesfully stablished or false if the connection process fails or if it has not yet completed (<$ssh-error>> can be used to differentiate between both cases).

$ssh->mux_socket_path

Returns the path to the socket where OpenSSH listens for new multiplexed connections.

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

Taken for example the method Net::OpenSSH system method:

  $ssh->system("ls -l *");
  $ssh->system('ls', '-l', '/');

The first call passes the argument unchanged to ssh, so that it is executed in the remote side through the user default shell that interprets shell metacharacters.

The second call passes the arguments unchanged to the command.

Under the hood, as the Secure Shell protocol does not have provision 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 comand list.

All the methods that invoke a remote command (system, open_ex, etc.) accept the option quote_args that allows 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.

As shell quoting is a tricky matter, I expect bugs to pop up in this area. You can see how ssh is called, and the quoting used setting the corresponding debug flag:

  $Net::OpenSSH::debug |= 16;

SEE ALSO

OpenSSH client documentation: ssh(1), ssh_config(5).

Core perl documentation perlipc, "open" in perlfunc, "waitpid" in perlfunc.

IO::Pty to known how to use the pseudo tty objects returned by several methods on this package.

Net::SFTP::Foreign provides a compatible SFTP implementation.

Expect can be used to interact with commands run through this module on the remote machine.

Other Perl SSH clients: Net::SSH::Perl, Net::SSH2, Net::SSH, Net::SSH::Perl.

BUGS AND SUPPORT

This is a very early release, expect lots of bugs. Also the API is provisional and will be changed as required in order to improve the module.

Does not work on Windows. I don't believe that could be done without becoming insane on the process, though, patches are very welcome!

Doesn't work on VMS either... well, actually, it probably doesn't work on anything not resembling a modern Linux/Unix OS.

Only tested on Linux with OpenSSH 5.1p1.

Currently no shell escaping is done when sending commands to the remote machine. I plan to change that in order to mimic system or exec Perl builtins behaviour.

To report bugs send my an email to the address that appear below or use the CPAN bug tracking system.

For questions related to module usage, you can also contact my by email but I would prefer if you post them in PerlMonks (that I read frequently), so other people can also find them.

TODO

- add scp support, either using the binary client or implementing the "protocol" in a new module.

- add expect method

- passphrase handling

Send your feature requests, ideas or any feedback, please!

COPYRIGHT AND LICENSE

Copyright (C) 2008 by Salvador Fandiño (sfandino@yahoo.com)

This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself, either Perl version 5.10.0 or, at your option, any later version of Perl 5 you may have available.