Net::OpenSSH(3)
๐ Net::OpenSSH(3) ๐
Okay bestie, welcome to the manual page for Net::OpenSSH โ that's the Net::OpenSSH(3) manpage, filed under User Contributed Perl Documentation. Grab a snack, this one's a whole saga ๐
โจ NAME โจ
Net::OpenSSH โ a 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\n";
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;
Look at all those little snippets, they're so cute, they're literally the entire vibe of the module in one block ๐
๐ฆ DESCRIPTION ๐ฆ
So. Net::OpenSSH is a secure shell client package that's implemented on top of the OpenSSH binary client (ssh). Yes, the actual binary. It's giving "stand on the shoulders of giants" energy and honestly? Iconic ๐
๐ Under the hood ๐
This package is built around the multiplexing feature that showed up in later versions of OpenSSH โ that feature is what lets you run several sessions over a single SSH connection. Quick history flex: OpenSSH 4.1 was the first one to provide all the required functionality, so that's the bar, bestie โญ
The way it works: when a new Net::OpenSSH object gets created, the OpenSSH ssh client runs in master mode, and it establishes a persistent connection to the server โ persistent for the entire lifetime of the object, no cap.
Then, every single time a new operation is requested, a new ssh process is started in slave mode, effectively reusing that master SSH connection to send the request on over to the remote side. Chef's kiss, so efficient, we love to see it ๐
๐ Net::OpenSSH Vs. Net::SSH::.* modules ๐
Okay so the big question: why would you use Net::OpenSSH instead of literally any of the other Perl SSH clients out there?
Well. Here's the author's own (self-admittedly biased) opinion, and I'm relaying it faithfully because that's the gig ๐ซถ
Net::SSH::Perl is not well maintained nowadays โ update: a new maintainer has stepped in so this situation could change!!! ๐ โ and it requires a bunch of modules (some of them very difficult to install) just to be acceptably efficient, plus its API is limited in some ways.
Net::SSH2 is much better than Net::SSH::Perl, but it's not completely stable yet. It can be very difficult to install on some specific operating systems, and its API is also limited โ in the same way as Net::SSH::Perl.
Net::SSH::Expect, in general, is a bad idea. Like, genuinely. Handling interaction with a shell via Expect in a generic way just can not be reliably done. That's the whole thing, no notes ๐
Net::SSH is just a wrapper around whatever SSH binary commands happen to be available on the machine. It can be very slow because they establish a new SSH connection for every operation performed. Every. Single. One. ๐ญ
In comparison, Net::OpenSSH is a pure perl module with no mandatory dependencies โ obviously besides requiring OpenSSH binaries, let's be reasonable ๐ธ
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 (e.g. IPC::Open2).
It's also very fast. The overhead introduced by launching a new ssh process for every operation is not appreciable (at least on the author's Linux box). The bottleneck is the latency intrinsic to the protocol, so Net::OpenSSH is probably as fast as an SSH client can be. Slay ๐
Being based on OpenSSH is also an advantage: you get a proved, stable, secure (to paranoid levels), inseparably and well maintained implementation of the SSH protocol. Security queen behavior ๐
On the other hand โ and I need you to hear this โ Net::OpenSSH does not work on Windows, not even under Cygwin. ๐ Sorry bestie.
Net::OpenSSH specifically requires the OpenSSH SSH client (AFAIK, the multiplexing feature is not available from any other SSH client). However โ important nuance โ 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).
Also, quick note: Net::OpenSSH and Net::SSH2 do not support version 1 of the SSH protocol. Version 1 who? Never heard of her ๐
๐ API ๐
โญ Optional arguments โญ
Almost all methods in this package accept, as their first argument, an optional reference to a hash containing parameters (\%opts). For instance, these two method calls are totally equivalent:
my $out1 = $ssh->capture(@cmd);
my $out2 = $ssh->capture({}, @cmd);
Same energy, different spelling ๐
๐ Error handling ๐
Most methods return undef (or an empty list) to indicate failure. Classic.
The error method can always be used to explicitly check for errors, and honestly you should be checking, bestie. 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 โ main character energy, every one of them:
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 โ which is lowkey unhinged but okay โ so 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. It's there for you, bestie ๐ซถ
Accepted options:
user => $user_nameโ Login name ๐port => $portโ TCP port number where the server is runningpassword => $passwordโ 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. Seriously. I'm not being cute about this one ๐
passphrase => $passphraseโ Uses the given passphrase to open the 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::Gatewaymethod, 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"onssh_config(5)) ๐ธbatch_mode => 1โ Disables querying the user for password and passphrases. No prompts, no waiting, no vibes.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. Yes, it will just straight up refuse you ๐ซ
By default ~/.libnet-openssh-perl is used.
ctl_path => $pathโ Path to the SSH master control socket.
Usually this option should be avoided, as the module is able to pick an unused socket path by itself. An exception to that rule is when the "external_master" feature is enabled.
Note that the length of the path is usually limited to between 92 and 108 bytes, depending of the underlying operating system. That's it, that's the whole budget ๐
ssh_cmd => $cmdโ Name or full path to the OpenSSHsshbinary. For instance:
my $ssh = Net::OpenSSH->new($host, ssh_cmd => '/opt/OpenSSH/bin/ssh');
scp_cmd => $cmdโ Name or full path to the OpenSSHscpbinary.
By default it is inferred from the ssh one.
rsync_cmd => $cmdโ Name or full path torsyncbinary. Defaults torsync.remote_shell => $nameโ Name of the remote shell. Used to select the argument quoter backend ๐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 methodscapture,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. Brutal. Efficient. Necessary ๐
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!!! For real, this one's the "hold my iced coffee" of options ๐ญ
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 established 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 /');
}
Parallel connections are so main character, I can't ๐ฆ
connect => 0โ Do not launch the master SSH process yet.master_opts => [...]โ Additional options to pass to thesshcommand 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 foropen_exand derived methods.
For instance:
my $ssh = Net::OpenSSH->new($host,
default_ssh_opts => [-o => "ConnectionAttempts=0"]);
So these next constructor options are still living in Net::OpenSSH->new territory, and honestly? They ate. ๐
Hereโs every single one, no skipping, no cap.
forward_agent => 1,forward_agent => 'always'โ Enables forwarding of the authentication agent. When"always"is passed as the argument, agent forwarding will be enabled by default in all the channels created from the object. Otherwise, it will have to be explicitly requested when calling the channel creating methods (i.e.open_exand its derivations). This option can not be used when passing a passphrase (viapassphrase) to unlock the login private key. Note that Net::OpenSSH will not runssh-agentfor you. This has to be done ahead of time and the environment variableSSH_AUTH_SOCKset pointing to the proper place. โจforward_X11 => 1โ Enables forwarding of the X11 protocol. ๐ฅ๏ธdefault_stdin_fh => $fh,default_stdout_fh => $fh,default_stderr_fh => $fhโ Default I/O streams foropen_exand derived methods (currently, that means any method butpipe_inandpipe_outand 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 file names and use them 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_pathmust also be passed when this option is set. See alsoget_ctl_path. Example:
$ssh = Net::OpenSSH->new('foo', external_master => 1, ctl_path = $path);
When external_master is set, the hostname argument becomes optional (0.0.0.0 is passed to OpenSSH which does not use it at all).
default_encoding => $encoding,default_stream_encoding => $encoding,default_argument_encoding => $encodingโ Set default encodings. See"Data encoding". ๐งpassword_prompt => $string,password_prompt => $reโ By default, when using password authentication, the module expects the remote side to send a password prompt matching/[?:]/. This option can be used to override that default for the rare cases when a different prompt is used. Examples:
password_prompt => ']'; # no need to escape ']'
password_prompt => qr/[:?>]/;
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 repeatedly ascustom_login_handler($ssh, $pty, $data)where$sshis the current Net::OpenSSH object,ptyaIO::Ptyobject attached to the slavesshprocess tty and$dataa reference to an scalar you can use at will. The login handler must return1after the login process has completed successfully or0in 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 theasyncandtimeoutfeatures to work). See also the sample scriptlogin_handler.plin theexamplesdirectory. Usage of this option is incompatible with thepasswordandpassphraseoptions, you will have to handle password or passphrases from the custom handler yourself. ๐ซถmaster_setpgrp => 1โ When this option is set, the master process is run as a different process group. As a consequence it will not die when the user presses Ctrl+C at the terminal. In order to allow the master SSH process to request any information from the user, the module may set it as the terminal controlling process while the connection is established (usingtcsetpgrpinPOSIX). Afterwards, the terminal controlling process is reset. This feature is highly experimental. Report any problems you may find, please. ๐ญmaster_pty_force => 1โ By default, Net::OpenSSH attaches the master SSH process to a pty only when some kind of interactive authentication is requested. If this flag is set a pty will be attached always. That allows to get better diagnostics for some kind of errors (as for instance, bad host keys) and also allows to retrieve the pty log usingget_master_pty_log. ๐ฅ
$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_master_pty_log
In order to handle password authentication or entering the passphrase for a private key, Net::OpenSSH may run the master SSH process attached to a pty.
In that case and after a constructor call returns a connection failure error, this method can be called to retrieve the output captured at the pty (the log is discarded when the connection is established successfully).
Any data consumed from the pty by custom login handlers will be missing from the returned log. ๐
$ssh->get_user
$ssh->get_host
$ssh->get_port
Each one returns the corresponding SSH login parameter. ๐ธ
$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 which, probably, you do not 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 tostdin_pipe, but instead of a regular pipe it uses a pseudo-tty (pty). Note that on some operating systems (e.g. 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$fhand 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/nullas 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 requiresstdin_ptyto be also set.stdout_fh => $fhโ Duplicates$fhand 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/nullas the remote process stdout stream.stdinout_socket => 1โ Creates a new socketpair, attaches the stdin an stdout streams of the slave SSH process to one end and returns the other as the first value ($in) andundeffor 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 thedpipe(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$fhand 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โ tellssshto give the remote process a pseudo-tty ๐ by default a tty gets allocated whenever the remote command's stdin stream is attached to a tty. But heads up: when you set this flag and stdin is not attached to a tty, the ssh master and slave processes may spit out spurious warnings about failed tty operations ๐ญ that's not you, that's a bug present in older versions of OpenSSH.close_slave_pty => 0โ so when a pseudo pty is used for the stdin stream, the slave side is automatically closed on the parent process after forking thesshcommand. This option disables that feature, so the slave pty can actually be reached from the parent process as$pty->slaveโจ and then you have to close it yourself, explicitly (see IO::Pty).quote_args => $boolโ see "Shell quoting" below, bestie ๐remote_shell => $shellโ sets the remote shell, which lets you change the argument quoting mechanism in a per-command fashion. Super useful when you're talking to a Windows machine where argument parsing may be done at the command level in custom ways ๐ช
Example:
$ssh->system({remote_shell => 'MSWin'}, echo => $line);
$ssh->system({remote_shell => 'MSCmd,MSWin'}, type => $file);
forward_agent => $boolโ turns forwarding of the authentication agent on/off. Only usable when agent forwarding has been previously requested on the constructor, no cap ๐forward_X11 => $boolโ same deal, but for forwarding of the X11 protocol. Again, only usable when X11 forwarding has been previously requested on the constructor ๐ฅ๏ธssh_opts => \@optsโ a list of extra options for thesshcommand. Use this one with care, fr fr: 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 on the remote host, this option tells Net::OpenSSH to create a TCP tunnel ๐ the arguments become the target IP and port, or the remote path for a Unix socket.
Example:
my ($in, $out, undef, $pid) = $ssh->open_ex({tunnel => 1}, $IP, $port);
my ($in, $out, undef, $pid) = $ssh->open_ex({tunnel => 1}, $socket_path);
See also "Tunnels".
subsystem => $boolโ requests a connection to an SSH subsystem ๐ the name of the subsystem has to be passed as an argument, like this:
my $s = $ssh->open2socket({subsystem => 1}, 'netconf');
encoding => $encodingargument_encoding => $encodingโ sets 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);
๐ธ setpgrp => 1 ๐ธ
Calls setpgrp after forking the child process ๐ which means it won't die when the user presses Ctrl+C at the console. See also "setpgrp" in perlfunc.
Using this option without also setting master_setpgrp on the constructor call is mostly useless, because the signal will be delivered to the master process and all the remote commands aborted ๐ฌ this feature is experimental, so like, be aware.
๐ $ssh->system(\%opts, @cmd) ๐
Runs the command @cmd on the remote machine ๐ป returns true on success, undef otherwise.
The error status is set to OSSH_SLAVE_CMD_FAILED when the remote command exits with a non zero code (that code is available from $?, see "$?" in perlvar).
Example:
$ssh->system('ls -R /')
or die "ls failed: " . $ssh->error";
Just like the system builtin, the 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 โ so don't do that ๐
Accepted options, bestie:
stdin_data => $inputstdin_data => \@inputโ sends the given data through the stdin stream to the remote process ๐จ for example, this 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 gets aborted once$timeoutseconds have elapsed with no network activity โฑ๏ธ see also "Timeouts".async => 1โ does not wait for the child process to exit, and returns the PID of the new process instead ๐โโ๏ธ note that when this option is combined withstdin_data, the given data will be transferred to the remote side before control returns to the caller. See also thespawnmethod documentation below.stdin_fh => $fhstdin_discard => $boolstdout_fh => $fhstdout_discard => $boolstderr_fh => $fhstderr_discard => $boolstderr_to_stdout => $boolstdinout_dpipe => $cmdtty => $boolโ see theopen_exmethod documentation for an explanation of these options ๐stdin_keep_open => $boolโ whenstdin_datais given, the module closes the stdin stream once all the data has been sent. Unfortunately ๐ญ some SSH buggy servers fail to handle this event correctly and close the channel prematurely. As a workaround, when this flag is set the stdin is left open until the remote process terminates ๐ซถ
๐ $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.
Important: the error status is not set to OSSH_SLAVE_CMD_FAILED when the remote command exits with a non-zero code, okay?
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 supports the same set of options as system, except async and tunnel โ๏ธ
โญ $output = $ssh->capture(\%opts, @cmd) โญ
โญ @output = $ssh->capture(\%opts, @cmd) โญ
Conceptually this one is equivalent to the perl backquote operator (e.g. `ls`): it runs the command on the remote machine and captures its output ๐ธ
In scalar context it returns the output as a scalar. In list context it returns the output broken into lines (it honors $/, see "$/" in perlvar) ๐
The exit status of the remote command comes back in $?.
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 => $inputstdin_data => \@inputstdin_keep_open => $boolโ see thesystemmethod documentation for an explanation of these options.timeout => $timeoutโ see "Timeouts".stdin_fh => $fhstdin_discard => $boolstderr_fh => $fhstderr_discard => $boolstderr_to_stdout => $booltty => $boolโ see theopen_exmethod 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, same as above.
The accepted options are:
stdin_data => $inputstdin_data => \@inputstdin_keep_open => $boolโ see thesystemmethod documentation for an explanation of these options.timeout => $timeoutโ see "Timeouts".stdin_fh => $fhstdin_discard => $booltty => $boolโ see theopen_exmethod 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
โฆexcept it runs @cmd on the remote machine ๐ฐ๏ธ (see "open" in perlfunc).
No options are currently accepted.
There's no need to perform a waitpid on the returned PID, because 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 the previous method, it's equivalent to:
$pid = open $out, '-|', @cmd
โฆrunning @cmd on the remote machine ๐
No options are currently accepted.
๐ Shortcut city ๐
($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 the open_ex method, periodt โจ
๐ $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, okay? Don't ghost it ๐
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;
Okay quick vibe check though ๐
โ do not use spawn to kick off detached remote processes, the kind that are supposed to outlive your local program. That's just not what it's for, bestie. (The FAQ has the whole tea on running remote processes detached, go peek ๐ซ.)
โจ ($socket, $pid) = $ssh->open_tunnel(\%opts, $dest_host, $port) and ($socket, $pid) = $ssh->open_tunnel(\%opts, $socket_path)
Basically open2socket's sibling, but instead of running a command it pops open a TCP tunnel to whatever address you hand it. Also see the "Tunnels" section ๐.
โจ $out = $ssh->capture_tunnel(\%opts, $dest_host, $port) and @out = $ssh->capture_tunnel(\%opts, $dest_host, $port)
Same energy as capture, except it opens a TCP tunnel instead of running a command. Obsessed tbh.
Example, because yes:
$out = $ssh->capture_tunnel({stdin_data => join("\r\n",
"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) and $ssh->scp_put(\%opts, $local, $local2,..., $remote_dir_or_file)
These two are lil wrappers around the scp command, so you can move files to/from the remote host using the SSH master connection you already have โ recycling, iconic, mother earth is proud ๐.
When you're transferring several files, the target argument has to point to an existing directory. If it's just one file, the target can be a directory, a file name, or you can straight up omit it. Like:
$ssh->scp_get({glob => 1}, '/var/tmp/foo*', '/var/tmp/bar*', '/tmp');
$ssh->scp_put('/etc/passwd');
Both scp_get and scp_put return a true value when everything transferred correctly, otherwise you get undef ๐ญ.
Options they accept:
quiet => 0โ by defaultscpgets called with the quiet flag-qon, to shut up the progress info. This option lets you turn the progress bar back on. It's giving "I want to watch it go" ๐verbose => 1โ callsscpwith the-vflag.recursive => 1โ copies files and directories recursively, all the way down ๐glob => 1โ turns on shell metacharacter expansion in the sources list so you can use wildcards to pick files.glob_flags => $flagsโ the second argument passed to theFile::Glob::bsd_globfunction. Heads up: only available for thescp_putmethod โ ๏ธcopy_attrs => 1โ copies modification times, access times and modes from the original files. preserving the metadata, we love to see it ๐bwlimit => $Kbitsโ limits the bandwidth used, in Kbit/s.timeout => $secsโ the transfer gets aborted if the connection doesn't finish before the given timeout elapses. See also "Timeouts" โฐasync => 1โ doesn't wait for thescpcommand to finish. When you use this, the method returns the PID of the childscpprocess.
So yes, you can transfer files to several hosts in parallel, like this:
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 . "\n";
}
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)\n";
}
else {
redo if ($! == EINTR);
warn "waitpid($pid) failed: $!\n";
}
}
}
stdout_fh => $fh,stderr_fh => $fh,stderr_to_stdout => 1โ these get passed straight through, unchanged, to theopen_exmethod, so you can capture the output of thescpprogram. โจ
Fair warning: scp will not generate progress reports unless its stdout stream is attached to a tty. Just so you're not sitting there like ๐๏ธ๐๐๏ธ waiting.
ssh_opts => \@optsโ a list of extra options for thesshcommand.
Use this one with care: the module does not check the options you give it in any way, and they could mess with it. You've been warned ๐
๐ฆ $ssh->rsync_get(\%opts, $remote1, $remote2,..., $local_dir_or_file) and $ssh->rsync_put(\%opts, $local1, $local2,..., $remote_dir_or_file)
These use rsync over SSH to move files from/to the remote machine โ the fancy one, the upgraded one, main character energy ๐
They accept the same set of options as the scp ones above.
Any option they don't recognize gets passed as an argument to the rsync command (go read rsync(1) bestie). And plot twist: you can use underscores 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)
Makes you a brand new Net::SFTP::Foreign object for SFTP things, and it runs through the ssh master connection you already have. no extra setup, no drama ๐
โญ @call = $ssh->make_remote_command(\%opts, @cmd) and $call = $ssh->make_remote_command(\%opts, @cmd)
This one hands you back the arguments you need to run a command on the remote machine via SSH. Handy af:
my @call = $ssh->make_remote_command(ls => "/var/log");
system @call;
In scalar context it returns the arguments quoted and joined into one single string:
my $remote = $ssh->make_remote_comand("cd /tmp/ && tar xf -");
system "tar cf - . | $remote";
Options it takes:
tty => $boolโ enables/disables allocating a tty on the remote side.forward_agent => $boolโ enables/disables forwarding of the authentication agent.
Heads up: this option can only be used when agent forwarding was already requested on the constructor. no retroactive vibes ๐
tunnel => 1โ returns a command that creates a connection to some TCP server reachable from the remote host. In that case the arguments are the destination address and port. Like:
$cmd = $ssh->make_remote_command({tunnel => 1}, $host, $port);
subsystem => 1โ returns a command for invoking an SSH subsystem (think SFTP or netconf). In that case the only argument is the subsystem name ๐ฐ๏ธ
๐ $ssh->wait_for_master($async)
When the connection was established by calling the constructor with the async option, this call lets you advance the process. move it along, keep it going.
If $async is true, it'll do any work that can be done immediately without waiting โ entering the password, checking whether the multiplexing socket exists, that kind of thing โ and then it returns. If you give it a false value, it finalizes the whole connection process and waits until the multiplexing socket is actually available โณ
It returns a true value once the connection has been successfully established. False comes back if the connection process fails, or if it hasn't completed yet โ and then you can use the error method to tell those two cases apart ๐
From version 0.64 upwards: undef is returned when the master is still in an unstable state (login, killing, etc.) and 0 when it's in a stable state (running, stopped or gone). Numbers, bestie, they mean things ๐ข
๐ $ssh->check_master
Runs a whole bunch of checks to make sure the master connection is still alive. like a wellness check but for processes ๐ซถ
๐ $ssh->shell_quote(@args)
Returns the list of arguments, quoted so they'll come back to their original form when the remote shell parses them. nothing gets mangled, nothing gets eaten by the shell ๐
In scalar context it returns the list of arguments quoted and joined.
Usually the module does this task automatically for you โ 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)
Like the previous shell_quote, but it leaves wildcard characters unquoted so they can actually do their wildcard thing โจ
It can be used as a class method too.
๐ $ssh->set_expand_vars($bool)
Enables/disables the variable expansion feature (see "Variable expansion" below).
๐ $ssh->get_expand_vars
Returns the current state of the variable expansion feature. is it on or is it off, the people want to know ๐
๐ $ssh->set_var($name, $value) and $ssh->get_var($name, $value)
These two let you change and retrieve the value of the given name. ๐
๐ $ssh->get_master_pid
Returns the PID of the master SSH process. the actual number, the whole identity ๐
๐ $ssh->master_exited
This method lets you tell the module that the master process has exited, for when you grab its PID from some external wait or waitpid call. Like so:
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;
}
}
Genuinely important: if your program reaps the master process and this method doesn't get called, the OS could reassign that PID to some new unrelated process โ and then the module would try to kill that at object destruction time. not the vibe. not the vibe at all ๐
๐ $ssh->disconnect($async)
Shuts the SSH connection down. bye bestie ๐
Usually you don't need to call this explicitly โ just let the Net::OpenSSH object go out of scope and it handles itself.
If async is true, it doesn't wait for the SSH connection to terminate. In that case, wait_for_master must be called repeatedly until the shutdown sequence terminates (see the "AnyEvent" integration section below). ๐
๐ $ssh->restart($async)
Restarts the SSH session: closes any open connection and creates a new one. Any open channel also gets killed. fresh start, clean slate, rebrand ๐ธ
Note: calling this method may request the password or passphrase from the user again. so like, be ready ๐
In asynchronous mode, this method requires the connection to be terminated before it gets called. Afterwards, wait_for_master should be called repeatedly until the new connection is established. For instance:
my $async = 1;
$ssh->disconnect($async);
while (1) {
defined $ssh->wait_for_master($async) # returns 0 when the
# disconnect process
# finishes
and last;
do_something_else();
}
$ssh->restart($async);
while (1) {
defined $ssh->wait_for_master($async)
and last;
do_something_else();
}
$pid = $ssh->sshfs_import(\%opts, $remote_fs, $local_mnt_point) $pid = $ssh->sshfs_export(\%opts, $local_fs, $remote_mnt_point)
Okay bestie, these two use sshfs(1) to import or export a file system through the SSH connection. File-system slay via SSH โจ
They return the $pid of the "sshfs" process or of the slave "ssh" process used to proxy it. Killing that process unmounts the file system, though it may be probably better to use fusermount(1). iykyk ๐
The options accepted are as follows:
ssh_opts => \@ssh_optsโ options passed to the slave"ssh"process.sshfs_opts => \@sshfs_optsโ options passed to the"sshfs"command. For instance, to mount the file system in read-only mode:
my $pid = $ssh->sshfs_export({sshfs_opts => [-o => 'ro']},
"/", "/mnt/foo");
Note that this command requires a recent version of "sshfs" to work (at the time of writing, it requires the yet unreleased version available from the FUSE git repository!). not me warning you about unreleased software ๐ญ
See also the sshfs(1) man page and the "sshfs" and FUSE web sites at https://github.com/libfuse/sshfs and https://github.com/libfuse/libfuse respectively. web links, but make it manual-page chic ๐ฆ
$or = $ssh->object_remote(@args)
Returns an Object::Remote::Connection instance running on top of the Net::OpenSSH connection. object remote era ๐
Example:
my $or = $ssh->object_remote;
my $hostname = Sys::Hostname->can::on($or, 'hostname');
say $hostname->();
See also Object::Remote.
$any = $ssh->any(%opts)
Wraps the current object inside a Net::SSH::Any one. wrapping it up, gift-style ๐
Example:
my $any = $ssh->any;
my $content = $any->scp_get_content("my-file.txt");
$pid = $ssh->disown_master
Under normal operation Net::OpenSSH controls the life-time of the master "ssh" process, and when the object is destroyed the master process and any connection running over it are terminated. normal behavior: attached at the hip ๐ซถ
In some (rare) cases, it is desirable to let the master process and all the running connections survive. Calling this method does just that, it tells the Net::OpenSSH object that the master process is not its own anymore. main character master process goes independent ๐
The return value is the PID of the master process.
Note also that disowning the master process does not affect the operation of the module in any other regard.
For instance:
# See examples/sshfs_mount.pl for a working program
my $ssh = Net::OpenSSH->new($host);
my $sshfs_pid = $ssh->sshfs_import("/home/foo", "my-remote-home");
$ssh->disown_master;
$ssh->stop; # tells the master to stop accepting requests
exit(0);
$ssh->default_ssh_configuration
Allows one to retrieve the default SSH configuration for the target host from system files (i.e. "/etc/ssh/ssh_config") and user files ("~/.ssh/config"). config files, but make it accessible ๐ฟ
Under the hood, this method just calls "ssh -G $host" and returns the output unprocessed.
Example:
my $ssh = Net::OpenSSH->new($host, connect => 0);
my $txt = $ssh->default_ssh_configuration;
my @lines = split /^/m, $txt;
chomp @lines;
my %def_cfg = map split(/\s+/, $_, 2), @lines;
๐ 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. shell? not today, bestie ๐
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. spaces in paths: handled, periodt โจ
The shell quoting mechanism implements some extensions (for instance, performing redirections to /dev/null on the remote side) that can be disabled 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 which knows about file wildcards and passes them unquoted is used. The set of wildcards recognized currently is the one supported by bash(1). glob girl summer ๐ธ
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;
By default, the module assumes the remote shell is some variant of a POSIX or Bourne shell ("bash", "dash", "ksh", etc.). If this is not the case, the construction option "remote_shell" can be used to select an alternative quoting mechanism.
For instance:
$ssh = Net::OpenSSH->new($host, remote_shell => 'csh');
$ssh->system(echo => "hard\n to\n quote\n argument!");
Currently there are quoters available for POSIX (Bourne) compatible shells, "csh" and the two Windows variants "MSWin" (for servers using Win32::CreateProcess, see Net::OpenSSH::ShellQuoter::MSWin) and "MSCmd" (for servers using "cmd.exe", see Net::OpenSSH::ShellQuoter::MSCmd).
In any case, you can always do the quoting yourself and pass the quoted remote command as a single string:
# for VMS
$ssh->system('DIR/SIZE NFOO::USERS:[JSMITH.DOCS]*.TXT;0');
Note that 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. aliases said โnoโ and the full path said โbetโ ๐
โณ Timeouts
In order to stop remote processes when they timeout, the ideal approach 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:
- 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. SIGPIPE said โsurpriseโ ๐ญ
Remote processes may not access STDIN or STDOUT and even then, Net::OpenSSH can only close these channels when it is capturing them, so this approach does not always work.
- 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. orphan process behavior: not iconic ๐
Luckily, future versions of OpenSSH will support signaling remote processes via the mux channel. future OpenSSH glow-up โญ
๐ฎ 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"). order matters, bestie ๐
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. variable expansion ate that path up โจ
๐ Tunnels
Besides running commands on the remote host, Net::OpenSSH also allows one 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. tunnel vision, but make it network ๐ฆ
Example:
$ssh->system({tunnel => 1,
stdin_data => "GET / HTTP/1.0\r\n\r\n",
stdout_file => "/tmp/$server.res"},
$server, 80)
or die "unable to retrieve page: " . $ssh->error;
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);
or, y'know, capturing the output of several requests in parallel โ that's the one above, bestie, look at it, it's serving ๐
So like, under the hood, to create a tunnel, a brand new ssh process gets spawned with the option -W${address}:${port} (available from OpenSSH 5.4 and upwards), and it redirects its stdio streams to the remote given address. And here's the iconic part: unlike when ssh -L options are used to create tunnels, no TCP port is opened on the local machine at any time, so this is a perfectly secure operation. No cap. Actually secure. ๐ฅ
The PID of the new process is what the named methods hand back to you. You must reap it once the pipe or socket handlers for the local side of the tunnel have been closed. That's not optional, that's your homework. โจ
โ ๏ธ 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 (seesshd(8)andsshd_config(5)or the documentation provided by your SSH server vendor). So if it's not working, it might just be the vibes of your server admin, not you. ๐ซถ
๐ฆ Tunnels targeting UNIX sockets
When you're connecting to hosts running a recent version of OpenSSH sshd, you can also open connections targeting Unix sockets. Slay.
For instance:
my $response = $ssh->capture({tunnel => 1, stdin_data => $request },
"/tmp/socket-foo");
Currently, this feature requires a patched OpenSSH ssh client. The patch lives at patches/openssh-fwd-stdio-to-streamlocal-1.patch. Yes, you have to patch. I know. ๐ญ
๐ง Port forwarding
Real talk: Net::OpenSSH does not offer direct support for handling port forwardings between server and client. But bestie, it's literally fine, you can do it easily anyway by passing custom SSH options to its methods.
For instance, tunnel creation options can be passed to the constructor:
my $ssh = Net::OpenSSH->new(...
master_opts => -Llocalhost:1234:localhost:3306');
The port forwardings can also be changed for a running SSH connection using a Control command:
# setting up a tunnel:
$ssh->system({ssh_opts => ['-O','forward',
'-L127.0.0.1:12345:127.0.0.1:3306']});
# canceling it:
$ssh->system({ssh_opts => ['-O', 'cancel',
'-L127.0.0.1:12345:127.0.0.1:3306']});
Setup, cancel, setup, cancel. Main character behaviour honestly. ๐
๐ Data encoding
Okay so Net::OpenSSH has some support for transparently converting the data sent or received from the remote server into Perl's internal unicode representation. Cute, right? โจ
The methods that support this feature are the ones that move data from/to Perl data structures โ e.g. 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. So don't come for me if your pipe data is still raw. ๐
It's 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. Default vibes: latin1. Periodt.
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 sent and received on capture methods.argument_encoding => $encodingโ sets the encoding of the command line arguments.encoding => $encodingโ sets bothargument_encodingandstream_encoding. Two for one, iconic. ๐
The constructor also accepts default_encoding, default_stream_encoding and default_argument_encoding that set the defaults. Yes, you can set your defaults and never think about it again. ๐ธ
๐ Diverting new
When a code ref is installed at $Net::OpenSSH::FACTORY, calls to new will be diverted through it. Weird but slay.
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("\0", $class, map { $_ => $opts{$_} }, sort keys %opts);
my $old = $cache{signature};
return $old if ($old and $old->error != OSSH_MASTER_FAILED);
local $Net::OpenSSH::FACTORY = $old_factory;
$cache{$signature} = $class->new(%opts);
}
$Net::OpenSSH::FACTORY = \&factory;
... and I am sure it can be abused in several other ways! ๐ญ Not me saying that. Well. Lowkey saying that.
๐ 3rd PARTY MODULE INTEGRATION
๐ Expect
Sometimes you would like to use Expect to control some program running in the remote host. You can do it as follows:
my ($pty, $pid) = $ssh->open2pty(@cmd)
or die "unable to run remote command @cmd";
my $expect = Expect->init($pty);
Then, you will be able to use the new Expect object in $expect as usual. That's it. That's the whole thing. โจ
๐ฆ Net::Telnet
This example is adapted from Net::Telnet documentation:
my ($pty, $pid) = $ssh->open2pty({stderr_to_stdout => 1})
or die "unable to start remote shell: " . $ssh->error;
my $telnet = Net::Telnet->new(-fhopen => $pty,
-prompt => '/.*\$ $/',
-telnetmode => 0,
-cmd_remove_mode => 1,
-output_record_separator => "\r");
$telnet->waitfor(-match => $telnet->prompt,
-errmode => "return")
or die "login failed: " . $telnet->lastline;
my @lines = $telnet->cmd("who");
...
$telnet->close;
waitpid($pid, 0);
Look at that. waitpid($pid, 0) at the end like a responsible queen. ๐
๐ mod_perl and mod_perl2
mod_perl and mod_perl2 tie STDIN and STDOUT to objects that are not backed up by real file descriptors at the operating system level. Net::OpenSSH will fail if any of these handles is used explicitly or implicitly when calling some remote command. It's giving incompatible. ๐ญ
The work-around is to redirect them to /dev/null or to some file:
open my $def_in, '<', '/dev/null' or die "unable to open /dev/null";
my $ssh = Net::OpenSSH->new($host,
default_stdin_fh => $def_in);
my $out = $ssh->capture($cmd1);
$ssh->system({stdout_discard => 1}, $cmd2);
$ssh->system({stdout_to_file => '/tmp/output'}, $cmd3);
Also, note that from a security stand point, running ssh from inside the web server process is not a great idea. An attacker exploiting some Apache bug would be able to access the SSH keys and passwords and gain unlimited access to the remote systems. ๐จ Like, that's the whole kingdom. Gone.
๐
If you can, use a queue (as TheSchwartz) or any other mechanism to execute the ssh commands from another process running under a different user account. At a minimum, ensure that ~www-data/.ssh (or similar) is not accessible through the web server!
Please. For me. Protect the .ssh directory. ๐
๐ง Net::SFTP::Foreign
See method sftp.
๐ธ Net::SSH::Any
See method any.
โญ Object::Remote
See method object_remote.
๐ AnyEvent (and similar frameworks)
Net::OpenSSH provides all the functionality required to be integrated inside event oriented programming frameworks such as AnyEvent or IO::Async in the following way. Buckle up bestie, it's a four-step routine. ๐
- Create a disconnected Net::OpenSSH object:
my $ssh = Net::OpenSSH->new($host, async => 1, ...);
- Let the object connect to the remote host:
Use a timer to call the wait_for_master method in async mode repeatedly until it returns a true value indicating success.
Also, the object error state needs to be checked after every call in order to detect failed connections. For instance:
my $ssh = Net::OpenSSH->new(..., async => 1);
my $w;
$w = AE::timer 0.1, 0.1, sub {
if ($ssh->wait_for_master(1)) {
# the connection has been established!
# remote commands can be run now
undef $w;
on_ssh_success(...);
}
elsif ($ssh->error) {
# connection can not be established
undef $w;
on_ssh_failure(...);
}
}
- Use the event framework to launch the remote processes:
Call Net::OpenSSH make_remote_command to construct commands which can be run using the framework's regular facilities for launching external commands.
Error checking should also be performed at this point because the SSH connection could be broken. ๐
For instance:
if (defined(my $cmd = $ssh->make_remote_command(echo => 'hello!')) {
AnyEvent::Util::run_cmd($cmd, %run_cmd_opts);
}
else {
# something went wrong!
}
Alternatively, any of the open* methods provided by Net::OpenSSH could also be used to launch remote commands. Options on options, we love to see it. ๐
- When finished, disconnect asynchronously
After initiating an asynchronous disconnect with disconnect(1), repeatedly call wait_for_master until you get a defined but false value:
$ssh->disconnect(1);
my $w; $w = AE::timer 0.1, 0.1, sub {
my $res = $ssh->wait_for_master(1);
if (defined $res && !$res) {
undef $w;
undef $ssh;
}
};
๐จ Be careful not to let the $ssh object go out of scope until the disconnection has finished, otherwise its destructor will wait and block your program until the disconnection has completed. Nobody wants that. Not you, not your event loop, not anybody. ๐ญ
๐ Other modules
CPAN contains several modules that rely on SSH to perform their duties โ as for example IPC::PerlSSH or GRID::Machine. The catalogue is real. ๐๏ธ
Often, it is possible to instruct them to go through a Net::OpenSSH multiplexed connection employing some available constructor option. For instance:
use Net::OpenSSH;
use IPC::PerlIPC;
my $ssh = Net::OpenSSH->new(...);
$ssh->error and die "unable to connect to remote host: " . $ssh->error;
my @cmd = $ssh->make_remote_command('/usr/bin/perl');
my $ipc = IPC::PerlSSH->new(Command => \@cmd);
my @r = $ipc->eval('...');
or...
use GRID::Machine;
...
my @cmd = $ssh->make_remote_command('/usr/bin/perl');
my $grid = GRID::Machine->new(command => \@cmd);
my $r = $grid->eval('print "hello world!\n"');
In other cases, some kind of plugin mechanism is provided by the 3rd party modules to allow for different transports. The method open2 may be used to create a pair of pipes for transport in these cases. Pipes. For transport. We stan a flexible plugin system. ๐ซถโจ
๐งโจ TROUBLESHOOTING โจ๐ง
Okay bestie, so usually Net::OpenSSH just works right out of the box ๐, but when it doesn't, some people have a genuinely hard time figuring out why. This lil mini troubleshooting guide is here to help you find the problem and solve it. No cap.
1 - check the error message ๐
First thing: right after your Net::OpenSSH constructor call, add an error check, okay?
$ssh = Net::OpenSSH->new(...);
$ssh->error and die "SSH connection failed: " . $ssh->error;
That error message will literally tell you what went wrong. Read it first, bestie. ๐ญ
2 - Check the connection parameters ๐ซถ
Believe it or not, passing bad parameters to Net::OpenSSH is one of the top causes of failures โ so check that you're using the right ones, fr fr.
Specifically, if you're getting them from the outside, make sure they don't have extra spaces or newlines stuck to them. Do you need to chomp? ๐
Passwords and URIs may contain $ or @ characters. If you've hardcoded those in your script, check that they're quoted properly โ and BTW, use strict. Periodt.
3 - OpenSSH version ๐ฆ
Make sure you have a version of ssh that's recent enough:
$ ssh -V
OpenSSH_5.1p1 Debian-5, OpenSSL 0.9.8g 19 Oct 2007
OpenSSH version 4.1 was the first to support the multiplexing feature, and it's the minimal version the module needs to work. Honestly, I advise you to use the latest OpenSSH (currently 7.5). ๐
The ssh_cmd constructor option lets you pick which ssh binary to use. For example:
$ssh = Net::OpenSSH->new($host,
ssh_cmd => "/opt/OpenSSH/5.8/bin/ssh")
Some hardware vendors (e.g. Sun โ errโฆ Oracle ๐) include custom versions of OpenSSH bundled with the operating system. In principle, Net::OpenSSH should work with these SSH clients as long as they're derived from some version of OpenSSH that's recent enough. Anyway, my advice is: use the real OpenSSH software if you can! ๐ฏ
4 - run ssh from the command line ๐
Check that you can connect to the remote host using the same parameters you're passing to Net::OpenSSH. In particular, make sure you're running ssh as the same local user.
If you're running your script from a web server, that user is probably www, apache, or something like that.
Common problems are:
- Remote host public key not present in known_hosts file.
The SSH protocol uses public keys to identify remote hosts, so they can't be supplanted by some malicious third parties.
For OpenSSH, usually the server public key is stored in /etc/ssh/ssh_host_dsa_key.pub or in /etc/ssh/ssh_host_rsa_key.pub, and that key should be copied into the ~/.ssh/known_hosts file on the local machine (other SSH implementations may use other file locations).
Maintaining server keys when several hosts and clients are involved can be somewhat inconvenient, so most SSH clients, by default, when a new connection is made to a host whose key is not in the known_hosts file, show the key and ask the user if they want the key copied there.
- Wrong remote host public key in known_hosts file.
This is another common problem. It happens when a server is replaced or reinstalled from scratch and its public key changes, so it becomes different from the one installed in the known_hosts file.
The easiest way to solve it is to remove the old key from the known_hosts file by hand using any editor, then connect to the server replying yes when asked to save the new key.
- Wrong permissions for the
~/.sshdirectory or its contents.
The OpenSSH client performs several checks on the access permissions of the ~/.ssh directory and its contents, and refuses to use them when they're misconfigured. See the FILES section from the ssh(1) man page.
- Incorrect settings for password or public key authentication.
Check that you're using the right password, or that the user public key is correctly installed on the server.
5 - security checks on the multiplexing socket ๐
Net::OpenSSH performs some security checks on the directory where the multiplexing socket is going to be placed, to make sure other users can't access it.
The default location for the multiplexing socket is under ~/.libnet-openssh-perl. You can change it using the ctl_dir and ctl_path constructor arguments.
The requirements for that directory and all its parents are:
- They have to be owned by the user executing the script or by
root. - Their permission masks must be
0755or more restrictive, so nobody else has permissions to perform write operations on them.
The constructor option strict_mode disables these security checks โ but you should not use it unless you understand its implications, bestie. ๐จ
6 - file system must support sockets ๐
Some file systems (like FAT or AFS) do not support placing sockets inside them.
Make sure the ctl_dir path does not lay into one of those file systems. Vibe check your filesystem, okay? โจ
๐โจ DEBUGGING โจ๐
Debugging of Net::OpenSSH internals is controlled through the variable $Net::OpenSSH::debug. Every bit of this variable activates debugging of some subsystem, like this:
bit 1- errors โ Dumps changes on the internal object attribute where errors are stored.bit 2- ctl_path โ Dumps information aboutctl_pathcalculation and the tests performed on that directory in order to decide if it's secure to place the multiplexing socket inside.bit 4- connecting โ Dumps information about the establishment of new master connections.bit 8- commands and arguments โ Dumps the command and arguments for everysystem/execcall.bit 16- command execution โ Dumps information about the progress of command execution.bit 32- destruction โ Dumps information about the destruction ofNet::OpenSSHobjects and the termination of the SSH master processes.bit 64- IO loop โ Dumps information about the progress of the IO loop on capture operations.bit 128- IO hexdumps โ Generates hexdumps of the information that travels through the SSH streams inside capture operations.bit 512- OS tracing of the master process โ Use the moduleNet::OpenSSH::OSTracerto trace the SSH master process at the OS level.
For instance, in order to activate all the debugging flags, you can use:
$Net::OpenSSH::debug = ~0;
Note that the meaning of the flags and the information generated is only intended for debugging of the module, and may change without notice between releases. ๐ No promises, iykyk.
If you're using password authentication, enabling debugging for IO::Tty may also show interesting information:
$IO::Tty::DEBUG = 1;
Finally, by default debugging output is sent to STDERR. You can override it by pointing $Net::OpenSSH::debug_fh to a different file handle. For instance:
BEGIN {
open my $out, '>', '/tmp/debug.txt' or warn $!;
$Net::OpenSSH::debug_fh = $out;
$Net::OpenSSH::debug = -1;
}
๐ SECURITY ๐
Q: Is this module secure? A: Well, it tries to be! ๐
Okay so from a security standpoint, the whole goal of this module is to be as secure as OpenSSH, your operating system, your shell and in general your environment allow it to be. No cap โ it is not out here taking shortcuts just to make your life easier if that shortcut means lowering the security level (for instance, disabling StrictHostKeyChecking by default). That is not the vibe. ๐
โโ๏ธ
In code supporting features that are not just proxied to OpenSSH, the module tries to keep the same standards of security as OpenSSH โ for instance, checking directory and file permissions when placing the multiplexing socket. It is giving careful, responsible, checks-its-own-permissions energy. โจ
On the other hand, and keeping with OpenSSH philosophy, the module lets you disable most (all?) of those security measures. But just because it lets you do it does not mean it is a good idea to do so!!! Bestie, please. ๐ญ๐
If you are a novice programmer or SSH user, and googling you have just found some flag that you don't understand but that seems to magically solve your connection problems... well, believe me, it is probably a bad idea to use it. Ask somebody who really knows first! ๐
Just to make things clear: if your code contains any of the keywords from the (non-exclusive) list below and you don't know why, you are probably wrecking the security of the SSH protocol:
strict_modeStrictHostKeyCheckingUserKnownHostsFile
That list is lowkey a warning label. Do not ignore it. ๐
Other considerations related to security you may like to know are as follows:
๐งผ Taint mode ๐งผ
The module supports working in taint mode. Slay. โจ
If you are in an exposed environment, you should probably enable it for your script in order to catch any unchecked command for being executed in the remote side. It is literally there to help you catch sketchy stuff before it becomes a whole group-chat meltdown. ๐ซถ
๐ Web environments ๐
It is a bad idea to establish SSH connections from your webserver because if it becomes compromised in any way, the attacker would be able to use the credentials from your script to connect to the remote host and do anything he wishes there. Highkey do not do this. ๐ฉ๐ญ
Webserver + SSH credentials = not the cute little combo you think it is. If that webserver gets compromised, your script's credentials are basically handing over the remote host. ๐
๐ง Command quoting ๐ง
The module can quote commands and arguments for you in a flexible and powerful way. Obsessed. ๐
This is a feature you should use as it reduces the possibility of some attacker being able to inject and run arbitrary commands on the remote machine (and even for scripts that are not exposed it is always advisable to enable argument quoting). It is giving responsible, cautious, main-character security energy. ๐
Having said that, take into consideration that argument-quoting is just a hack to emulate the invoke-without-a-shell feature of Perl builtins such as system and alike. There may be bugs(*) on the quoting code, your particular shell may have different quoting rules with unhandled corner cases or whatever. So likeโฆ it is very good, but it is not a magic force field. โจ
If your script is exposed to the outside, you should check your inputs and restrict what you accept as valid. Validate your inputs, bestie. Fr fr. ๐ซถ
[* even if this is one of the parts of the module more intensively tested!]
Yes, it is intensively tested. Yes, you still validate your inputs. Both things can be true. ๐
๐ Shellshock ๐
(see Shellshock at http://en.wikipedia.org/wiki/Shellshock_%28software_bug%29)
When executing local commands, the module always avoids calling the shell so in this way it is not affected by Shellshock. Good news, honestly. โจ
Unfortunately, some commands (scp, rsync and ssh when the ProxyCommand option is used) invoke other commands under the hood using the user shell. That opens the door to local Shellshock exploitation. Not iconic. Not slay. Very much a security red flag. ๐ฉ๐ญ
On the remote side invocation of the shell is unavoidable due to the protocol design. That is just how the protocol works, no cap.
By default, SSH does not forward environment variables, but some Linux distributions explicitly change the default OpenSSH configuration to enable forwarding and acceptance of some specific ones (for instance LANG and LC_* on Debian and derivatives, Fedora does alike) and this also opens the door to Shellshock exploitation. So yeah, distro defaults can absolutely matter here. ๐
Note that the shell used to invoke commands is not /bin/sh but the user shell as configured in /etc/passwd, PAM or whatever authentication subsystem is used by the local or remote operating system. Debian users, don't think you are not affected because your /bin/sh points to dash! That plot twist is not the flex you think it is. ๐โจ
๐ FAQ ๐
Frequent questions about the module:
๐ป Connecting to switches, routers, etc.
Q: I can not get the method system, capture, etc., to work when connecting to some router, switch, etc. What I am doing wrong?
A: Okay so bestie, roughly the SSH protocol has two modes of operation: command mode and interactive mode.
Command mode is literally for running single commands on the remote host. It opens a SSH channel between both hosts, asks the remote computer to run some given command and when it finishes, the channel is closed. Itโs what you get, for instance, when you run something asโฆ
$ ssh my.unix.box cat foo.txt
โฆ and it is also the way Net::OpenSSH runs commands on the remote host. Slay.
Interactive mode launches a shell on the remote hosts with its stdio streams redirected to the local ones so that the user can transparently interact with it.
Some devices (as probably the one you are using) do not run an standard, general purpose shell (e.g. bash, csh or ksh) but some custom program specially targeted and limited to the task of configuring the device.
Usually, the SSH server running on these devices does not support command mode. It unconditionally attaches the restricted shell to any incoming SSH connection and waits for the user to enter commands through the redirected stdin stream.
The only way to work-around this limitation is to make your script talk to the restricted shell (1-open a new SSH session, 2-wait for the shell prompt, 3-send a command, 4-read the output until you get to the shell prompt again, repeat from 3). The best tool for this task is probably Expect, used alone or combined with Net::OpenSSH (see "Expect").
There are some devices that support command mode but that only accept one command per connection. In that cases, using Expect is also probably the best option.
Nowadays, there is a new player, Net::CLI::Interact that may be more suitable than Expect, and Net::Appliance::Session for working specifically with network devices.
๐ Connection fails
Q: I am unable to make the module connect to the remote hostโฆ
A: Have you read the troubleshooting section? (see "TROUBLESHOOTING").
๐ Disable StrictHostKeyChecking
Q: Why is ssh not run with StrictHostKeyChecking=no?
A: Using StrictHostKeyChecking=no relaxes the default security level of SSH and it will be relatively easy to end with a misconfigured SSH (for instance, when known_hosts is unwritable) that could be forged to connect to a bad host in order to perform man-in-the-middle attacks, etc.
I advice you to do not use that option unless you fully understand its implications from a security point of view.
If you want to use it anyway, past it to the constructor:
$ssh = Net::OpenSSH->new($host,
master_opts => [-o => "StrictHostKeyChecking=no"],
...);
๐ญ child process STDIN/STDOUT/STDERR is not a real system file handle
Q: Calls to system, capture, etc. fail with the previous error, whatโs happening?
A: The reported stdio stream is closed or is not attached to a real file handle (e.g. it is a tied handle). Redirect it to /dev/null or to a real file:
my $out = $ssh->capture({stdin_discard => 1, stderr_to_stdout => 1},
$cmd);
See also the mod_perl entry above.
โ๏ธ Solaris (and AIX and probably others)
Q: I was trying Net::OpenSSH on Solaris and seem to be running into an issueโฆ
A: The SSH client bundled with Solaris is an early fork of OpenSSH that does not provide the multiplexing functionality required by Net::OpenSSH. You will have to install the OpenSSH client.
Precompiled packages are available from Sun Freeware (http://www.sunfreeware.com). There, select your OS version an CPU architecture, download the OpenSSH package and its dependencies and install them. Note that you do not need to configure Solaris to use the OpenSSH server sshd.
Ensure that OpenSSH client is in your path before the system ssh or alternatively, you can hardcode the full path into your scripts as follows:
$ssh = Net::OpenSSH->new($host,
ssh_cmd => '/usr/local/bin/ssh');
AIX and probably some other unixen, also bundle SSH clients lacking the multiplexing functionality and require installation of the real OpenSSH.
๐ Can not change working directory
Q: I want to run some command inside a given remote directory but I am unable to change the working directory. For instance:
$ssh->system('cd /home/foo/bin');
$ssh->systen('ls');
does not list the contents of /home/foo/bin.
What am I doing wrong?
A: Net::OpenSSH (and, for that matter, all the SSH modules available from CPAN but Net::SSH::Expect) run every command in a new session so most shell builtins that are run for its side effects become useless (e.g. cd, export, ulimit, umask, etc., usually, you can list them running help from the shell).
A work around is to combine several commands in one, for instance:
$ssh->system('cd /home/foo/bin && ls');
Note the use of the shell && operator instead of ; in order to abort the command as soon as any of the subcommands fail.
Also, several commands can be combined into one while still using the multi-argument quoting feature as follows:
$ssh->system(@cmd1, \\'&&', @cmd2, \\'&&', @cmd3, ...);
๐ Running detached remote processes
Q: I need to be able to ssh into several machines from my script, launch a process to run in the background there, and then return immediately while the remote programs keep runningโฆ
A: If the remote systems run some Unix/Linux variant, the right approach is to use nohup(1) that will disconnect the remote process from the stdio streams and to ask the shell to run the command on the background. For instance:
$ssh->system("nohup $long_running_command &");
Also, it may be possible to demonize the remote program. If it is written in Perl you can use App::Daemon for that (actually, there are several CPAN modules that provided that kind of functionality).
In any case, note that you should not use spawn for that.
๐ MaxSessions server limit reached
Q: I created an $ssh object and then fork a lot children processes which use this object. When the children number is bigger than MaxSessions as defined in sshd configuration (defaults to 10), trying to fork new remote commands will prompt the user for the password.
A: When the slave SSH client gets a response from the remote servers saying that the maximum number of sessions for the current connection has been reached, it fall backs to open a new direct connection without going through the multiplexing socket.
To stop that for happening, the following hack can be used:
$ssh = Net::OpenSSH->new(host,
default_ssh_opts => ['-oConnectionAttempts=0'],
...);
๐ Running remote commands with sudo
Q: How can I run remote commands using sudo to become root first?
A: The simplest way is to tell sudo to read the password from stdin with the -S flag and to do not use cached credentials with the -k flag. You may also like to use the -p flag to tell sudo to print an empty prompt. For instance:
my @out = $ssh->capture({ stdin_data => "$sudo_passwd\n" },
'sudo', '-Sk',
'-p', '',
'--',
@cmd);
If the version of sudo installed on the remote host does not support the -S flag (it tells sudo to read the password from its STDIN stream), you can do it as follows:
my @out = $ssh->capture({ tty => 1,
stdin_data => "$sudo_passwd\n" },
'sudo', '-k',
'-p', '',
'--',
@cmd);
This may generate an spurious and harmless warning from the SSH master connection (because we are requesting allocation of a tty on the remote side and locally we are attaching it to a regular pair of pipes).
If for whatever reason the methods described above fail, you can always revert to using Expect to talk to the remote sudo. See the examples/expect.pl script from this module distribution.
๐ Interactive sessions
Q: How can I start an interactive remote session?
A: Just call the system method with an empty argument list:
my $ssh = Net::OpenSSH->new(...);
$ssh->system;
Q: How about running an interactive sftp session?
A: Programs that use an underlying ssh connection usually provide some way (for instance, command line option -o) to pass additional options for the ssh command used to run that connection. We just need to use such mechanism to pass the path to the control socket.
For instance, for the particular case of sftp:
$cp = $ssh->get_ctl_path;
system "sftp", "-oControlPath=$cp", $host;
๐ SEE ALSO ๐
okay so bestie, when youโre done obsessing over the main character of this page, hereโs the whole โจ extended universe โจ:
- OpenSSH client documentation
ssh(1),ssh_config(5), the project web<http://www.openssh.org>and its FAQ<http://www.openbsd.org/openssh/faq.html>.scp(1)andrsync(1). The OpenSSH Wikibook<http://en.wikibooks.org/wiki/OpenSSH>. Net::OpenSSH::Gatewayโ for detailed instruction about how to get this module to connect to hosts through proxies and other SSH gateway servers.- Core perl documentation
perlipc,"open" in perlfunc,"waitpid" in perlfunc. IO::Ptyโ so you know 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 (see also theexpect.pland<autosudo.pl>scripts in the examples directory).SSH::OpenSSH::Parallelโ an advanced scheduler that allows one to run commands in remote hosts in parallel. It is obviously based onNet::OpenSSH.SSH::Batchโ allows one to run remote commands in parallel in a cluster. It is build on top onNet::OpenSSHalso.- Other Perl SSH clients:
Net::SSH::Perl,Net::SSH2,Net::SSH,Net::SSH::Expect,Net::SCP,Net::SSH::Mechanize. Net::OpenSSH::Compatโ a package offering a set of compatibility layers for other SSH modules on top ofNet::OpenSSH.IPC::PerlSSH,GRID::Machineโ allow execution of Perl code in remote machines through SSH.SSH::RPCโ implements an RPC mechanism on top of SSH usingNet::OpenSSHto handle the connections.Net::CLI::Interactโ allows one to interact with remote shells and other services. It is specially suited for interaction with network equipment. The phrasebook approach it uses is very clever. You may also like to check the other modules<https://metacpan.org/author/OLIVER>from its author, Oliver Gorwits.
๐ BUGS AND SUPPORT ๐
bestie, this is the fine print thatโs still giving important โจ. read it before you come for the module, okay?
๐งช Experimental features ๐งช
- Support for the
restartfeature is experimental. Object::Remoteintegration is highly experimental.- Support for tunnels targeting Unix sockets is highly experimental.
- Support for the
setpgrpfeature is highly experimental. - Support for the gateway feature is highly experimental and mostly stalled.
- Support for taint mode is experimental.
๐ญ Known issues ๐ญ
Net::OpenSSH does not work on Windows. OpenSSH multiplexing feature requires passing file handles through sockets, something that is not supported by any version of Windows.
It does not work on VMS either... well, probably, it does not work on anything not resembling a modern Linux/Unix OS.
Old versions of OpenSSH ssh may leave stdio streams in non-blocking mode. That can result on failures when writing to STDOUT or STDERR after using the module. In order to work-around this issue, Perl fcntl in perlfunc can be used to unset the non-blocking flag:
use Fcntl qw(F_GETFL F_SETFL O_NONBLOCK);
my $flags = fcntl(STDOUT, F_GETFL, 0);
fcntl(STDOUT, F_SETFL, $flags & ~O_NONBLOCK);
๐ฃ Reporting bugs and asking for help ๐ฃ
To report bugs send an email to the address that appear below or use the CPAN bug tracking system at <http://rt.cpan.org>.
Post questions related to how to use the module in PerlMonks <http://perlmonks.org/>, you will probably get faster responses than if you address me directly and I visit PerlMonks quite often, so I will see your question anyway.
๐ผ Commercial support ๐ผ
Commercial support, professional services and custom software development around this module are available through my current company. Drop me an email with a rough description of your requirements and we will get back to you ASAP.
๐ My wishlist ๐
If you like this module and you are feeling generous, take a look at my Amazon Wish List: <http://amzn.com/w/1WU1P6IR5QZ42>.
Also consider contributing to the OpenSSH project this module builds upon: <http://www.openssh.org/donations.html>.
๐ฏ TODO ๐ฏ
- Tests for
scp_*,rsync_*andsftpmethods - Make
pipe_inandpipe_outmethodsopen_exbased auto_discard_streamsfeature for mod_perl2 and similar environments- Refactor open_ex support for multiple commands, maybe just keeping tunnel, ssh and raw
Send your feature requests, ideas or any feedback, please!
๐ ๏ธ CONTRIBUTING CODE ๐ ๏ธ
The source code of this module is hosted at GitHub: <http://github.com/salva/p5-Net-OpenSSH>.
Code contributions to the module are welcome but you should obey the following rules:
- Only Perl 5.8.4 required โ yes, that's pretty old, but
Net::OpenSSHis intended to be also used by system administrators that sometimes have to struggle with old systems. The reason to pick 5.8.4 is that it has been the default perl on Solaris for a long time. - Avoid the "All the world's a Linux PC" syndrome โ the module should work on any (barely) sane Unix or Linux operating system. Specially, it should not be assumed that the over-featured GNU utilities and toolchain are available.
- Dependencies are optional โ in order to make the module very easy to install, no mandatory dependencies on other CPAN modules are allowed. Optional modules, that are loaded only on demand, are acceptable when they are used for adding new functionality (as it is done, for instance, with
IO::Pty). Glue code for integration with 3rd party modules is also allowed (as it is done withExpect). Usage of language extension modules and alike is not acceptable. - Tests should be lax โ we don't want false negatives when testing. In case of doubt tests should succeed. Also, in case of tests invoking some external program, it should be checked that the external program is available and that it works as expected or otherwise skip those tests.
- Backward compatibility โ nowadays
Net::OpenSSHis quite stable and there are lots of scripts out there using it that we don't want to break, so, keeping the API backward compatible is a top priority. Probably only security issues could now justify a backward incompatible change. - Follow my coding style โ look at the rest of the code. I let Emacs do the formatting for me using
cperl-modePerlStyle. - Talk to me โ before making a large change or implementing a new feature get in touch with me. I may have my own ideas about how things should be done. It is better if you know them before hand, otherwise, you risk getting your patch rejected.
Well, actually you should know that I am quite good at rejecting patches but it is not my fault!
Most of the patches I get are broken in some way: they don't follow the main module principles, sometimes the author didn't get the full picture and solved the issue in a short-sighted way, etc.
In any case, you should not be discouraged to contribute. Even if your patch is not applied directly, seeing how it solves your requirements or, in the case of bugs, the underlying problem analysis may be very useful and help me to do it... my way.
I always welcome documentation corrections and improvements.
๐ COPYRIGHT AND LICENSE ๐
Copyright (C) 2008-2022 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.
๐ and thatโs the whole page, bestie! source/version is perl v5.40.2, dated 2025-01-03, and itโs Net::OpenSSH(3) โ iconic, no cap ๐โจ
๐ฆ where this page comes from
- alpine 3.22: perl-net-openssh-doc 0.84-r1 ยท GPL-1.0-or-later OR Artistic-1.0-Perl
- ๐ girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms