Net::SSH::Perl(3)

NAME
Net::SSH::Perl - Perl client Interface to SSH

SYNOPSIS
    use Net::SSH::Perl;
    my $ssh = Net::SSH::Perl->new($host);
    $ssh->login($user, $pass);
    my($stdout, $stderr, $exit) = $ssh->cmd($cmd);

DESCRIPTION
Net::SSH::Perl is an all-Perl module implementing an SSH (Secure Shell) client. It is compatible with both the SSH-1 and SSH-2 protocols.

Net::SSH::Perl enables you to simply and securely execute commands on remote machines, and receive the STDOUT, STDERR, and exit status of that remote command. It contains built-in support for various methods of authenticating with the server (password authentication, RSA challenge-response authentication, etc.). It completely implements the I/O buffering, packet transport, and user authentication layers of the SSH protocol, and makes use of external Perl libraries (in the Crypt:: family of modules) to handle encryption of all data sent across the insecure network. It can also read your existing SSH configuration files (/etc/ssh_config, etc.), RSA identity files, ECDSA identity files, Ed25519 identity files, known hosts files, etc.

One advantage to using Net::SSH::Perl over wrapper-style implementations of ssh clients is that it saves on process overhead: you no longer need to fork and execute a separate process in order to connect to an sshd. Depending on the amount of time and memory needed to fork a process, this win can be quite substantial; particularly if you're running in a persistent Perl environment (mod_perl, for example), where forking a new process is a drain on process and memory resources.

It also simplifies the process of using password-based authentications; when writing a wrapper around ssh you probably need to use Expect to control the ssh client and give it your password. Net::SSH::Perl has built-in support for the authentication protocols, so there's no longer any hassle of communicating with any external processes.

The SSH2 protocol support (present in Net::SSH::Perl as of version 1.00) is compatible with the SSH2 implementation in OpenSSH, and should also be fully compatible with the "official" SSH implementation. If you find an SSH2 implementation that is not compatible with Net::SSH::Perl, please let me know (email address down in AUTHOR & COPYRIGHTS); it turns out that some SSH2 implementations have subtle differences from others. AES-CTR ("aes256-ctr", "aes192-ctr", and "aes128-ctr") and Chacha20-Poly1305 ciphers are currently supported for SSH2 encryption. Deprecated ciphers AES-CBC ("aes256-cbc", "aes192-cbc", and "aes128-cbc") 3DES ("3des-cbc"), Blowfish ("blowfish-cbc"), and RC4 ("arcfour") are available but not enabled by default. One can enable them by using the Ciphers options parameter. For example:

    options => [ "Ciphers +aes256-cbc" ]

Using the + notation will append a cipher to the default ciphers list.

Integrity checking is performed by the "hmac-sha2-256", "hmac-sha2-512", "hmac-sha2-256-etm@openssh.com", or "hmac-sha2-512-etm@openssh.com" algorithms. The deprecated "hmac-sha1" or "hmac-md5" algorithms are available but not enabled by default. Many older SSH server installations still use hmac-sha1 as the main accepted MAC algorithm. To enable this, use the following options parameter:

    options => [ "MACs +hmac-sha1" ]

Compression, if requested, is limited to Zlib.

Supported server host key algorithms are "ssh-ed25519", "rsa-sha2-512", "rsa-sha2-256", "ecdsa-sha2-nistp521", "ecdsa-sha2-nistp384", "ecdsa-sha2-nistp256", and "ssh-rsa". Deprecated "ssh-dss" is supported but not enabled by default. It can be enabled with the options parameter:

    options => [ "HostKeyAlgorithms +ssh-dss" ]

Supported SSH2 public key authentication algorithms are the same.

Supported Key Exchange (KEX) algorithms are "diffie-hellman-group1-sha1", "diffie-hellman-group14-sha1", c<diffie-hellman-group14-sha256>, "diffie-hellman-group16-sha512", "diffie-hellman-group18-sha512", "diffie-hellman-group-exchange-sha256", "diffie-hellman-group-exchange-sha1", and "curve25519-sha256@libssh.org"/"curve25519-sha256". The "diffie-hellman-group1-sha1" algorithm is disabled by default, but can be activated via the options parameter:

    options => [ "KexAlgorithms +diffie-hellman-group1-sha1" ]

If you're looking for SFTP support, take a look at Net::SFTP, which provides a full-featured Perl implementation of SFTP, and sits on top of Net::SSH::Perl. SFTP requires the usage of the SSH2 protocol.

BASIC USAGE
Usage of Net::SSH::Perl is very simple.

  Net::SSH::Perl->new($host, %params)
To set up a new connection, call the new method, which connects to $host and returns a Net::SSH::Perl object.

new accepts the following named parameters in %params:

•   protocol

    The protocol you wish to use for the connection: should be either 2, 1, '1,2' or '2,1'. The first two say, quite simply, "only use this version of the protocol" (SSH-2 or SSH-1, respectively). The latter two specify that either protocol can be used, but that one protocol (the first in the comma-separated list) is preferred over the other.

    For this reason, it's "safer" to use the latter two protocol specifications, because they ensure that either way, you'll be able to connect; if your server doesn't support the first protocol listed, the second will be used. (Presumably your server will support at least one of the two protocols. :)

    The default value is '1,2', for compatibility with OpenSSH; this means that the client will use SSH-1 if the server supports SSH-1. Of course, you can always override this using a user/global configuration file, or through using this constructor argument.

•   cipher

    Specifies the name of the encryption cipher that you wish to use for this connection. This must be one of the supported ciphers; specifying an unsupported cipher will give you an error when you enter algorithm negotiation (in either SSH-1 or SSH-2).

    In SSH-1, the supported cipher names are IDEA, DES, DES3, and Blowfish; in SSH-2, the supported ciphers are aes256-ctr, aes192-ctr, aes128-ctr, chacha20-poly1305@openssh.com. arcfour, blowfish-cbc, and 3des-cbc are deprecated and are not enabled by default. aes256-cbc, aes192-cbc, and aes128-cbc are also supported but not enabled by default as CBC is no longer considered secure.

    The default SSH-1 cipher is IDEA; the default SSH-2 ciphers are aes256-ctr, aes192-ctr, aes128-ctr, chacha20-poly1305@openssh.com.

•   ciphers

    Like cipher, this is a method of setting the cipher you wish to use for a particular SSH connection; but this corresponds to the Ciphers configuration option, where cipher corresponds to Cipher. This also applies only in SSH-2.

    This should be a comma-separated list of SSH-2 cipher names; the list of cipher names is listed above in cipher.

    This defaults to: chacha20-poly1305@openssh.com,aes256-ctr,aes192-ctr,aes128-ctr.

•   port

    The port of the sshd daemon to which you wish to connect; if not specified, this is assumed to be the default ssh port.

•   debug

    Set to a true value if you want debugging messages printed out while the connection is being opened. These can be helpful in trying to determine connection problems, etc. The messages are similar (and in some cases exact) to those written out by the ssh client when you use the -v option.

    Defaults to false.

•   interactive

    Set to a true value if you're using Net::SSH::Perl interactively. This is used in determining whether or not to display password prompts, for example. It's basically the inverse of the BatchMode parameter in ssh configuration.

    Defaults to false.

•   privileged

    Set to a true value if you want to bind to a privileged port locally. You'll need this if you plan to use Rhosts or Rhosts-RSA authentication, because the remote server requires the client to connect on a privileged port. Of course, to bind to a privileged port you'll need to be root.

    If you don't provide this parameter, and Net::SSH::Perl detects that you're running as root, this will automatically be set to true. Otherwise it defaults to false.

•   identity_files

    A list of identity files to be used in pubkey authentication. The value of this argument should be a reference to an array of strings, each string identifying the location of an identity file. Each identity file will be tested against the server until the client finds one that authenticates successfully.

    If you don't provide this, SSH1 authentication defaults to using $ENV{HOME}/.ssh/identity, and SSH2 authentication defaults to the three files $ENV{HOME}/.ssh/id_ed25519, $ENV{HOME}/.ssh/id_ecdsa, and $ENV{HOME}/.ssh/id_rsa.

•   strict_host_key_checking

    This corresponds to the StrictHostKeyChecking ssh configuration option. Allowed values are no, yes, or ask. no disables host key checking, e.g., if you connect to a virtual host that answers to multiple IP addresses. yes or ask enable it, and when it fails in interactive mode, you are asked whether to continue. The host is then added to the list of known hosts.

•   compression

    If set to a true value, compression is turned on for the session (assuming that the server supports it).

    Compression is off by default.

    Note that compression requires that you have the Compress::Zlib module installed on your system. If the module can't be loaded successfully, compression is disabled; you'll receive a warning stating as much if you having debugging on (debug set to 1), and you try to turn on compression.

•   compression_level

    Specifies the compression level to use if compression is enabled (note that you must provide both the compression and compression_level arguments to set the level; providing only this argument will not turn on encryption).

    This setting is only applicable to SSH-1; the compression level for SSH-2 Zlib compression is always set to 6.

    The default value is 6.

•   use_pty

    Set this to 1 if you want to request a pseudo tty on the remote machine. This is really only useful if you're setting up a shell connection (see the shell method, below); and in that case, unless you've explicitly declined a pty (by setting use_pty to 0), this will be set automatically to 1. In other words, you probably won't need to use this, often.

    The default is 1 if you're starting up a shell, and 0 otherwise.

•   terminal_mode_string

    Specify the POSIX terminal mode string to send when use_pty is set. By default the only mode set is the VEOF character to 0x04 (opcode 5, value 0x00000004). See RFC 4254 section 8 for complete details on this value.

•   no_append_veof

    (SSH-2 only) Set this to 1 if you specified use_pty and do not want Ctrl-D (0x04) appended twice to the end of your input string. On most systems, these bytes cause the terminal driver to return "EOF" when standard input is read. Without them, many programs that read from standard input will hang after consuming all the data on STDIN.

    No other modifications are made to input data. If your data contains 0x04 bytes, you may need to escape them.

    Set this to 0 if you have raw terminal data to specify on standard input, and you have terminated it correctly.

•   options

    Used to specify additional options to the configuration settings; useful for specifying options for which there is no separate constructor argument. This is analogous to the -o command line flag to the ssh program.

    If used, the value should be a reference to a list of option directives in the format used in the config file. For example:

        my $ssh = Net::SSH::Perl->new("host", options => [
            "BatchMode yes", "RhostsAuthentication no" ]);

    Available options are:

        BindAddress
        Host
        BatchMode
        ChallengeResponseAuthentication
        CheckHostIP
        Cipher
        Ciphers*
        Compression
        CompressionLevel
        DSAAuthentication
        FingerprintHash
        GlobalKnownHostsFile
        HashKnownHosts
        HostKeyAlgorithms*
        HostName
        IdentityFile
        KexAlgorithms*
        MACs*
        NumberOfPasswordPrompts
        PasswordAuthentication
        PasswordPromptHost
        PasswordPromptLogin
        Port
        Protocol
        RhostsAuthentication
        RhostsRSAAuthentication
        RSAAuthentication
        StrictHostKeyChecking
        UpdateHostKeys
        UsePrivilegedPort
        User
        UserKnownHostsFile

    * Indicates the +/- wildcard notation may be used.

    For example:

        MACs +hmac-sha1

    will add hmac-sha1 to the default MACs list.

    Or:

        Ciphers +aes*-cbc

    will add aes128-cbc, aes192-cbc, and aes256-cbc to the default Ciphers

    While:

        KexAlgorithms -*-sha512

    will remove all algorithms that end in -sha512 from the default list.

  $ssh->login([ $user [, $password [, $suppress_shell ] ] ])
Sets the username and password to be used when authenticating with the sshd daemon. The username $user is required for all authentication protocols (to identify yourself to the remote server), but if you don't supply it the username of the user executing the program is used.

The password $password is needed only for password authentication (it's not used for passphrases on encrypted RSA/DSA identity files, though perhaps it should be). And if you're running in an interactive session and you've not provided a password, you'll be prompted for one.

By default, Net::SSH::Perl will open a channel with a shell on it. This is usually what you want. If you are tunneling another protocol over SSH, however, you may want to prevent this behavior. Passing a true value in $suppress_shell will prevent the shell channel from being opened (SSH2 only).

  ($out, $err, $exit) = $ssh->cmd($cmd, [ $stdin ])
Runs the command $cmd on the remote server and returns the stdout, stderr, and exit status of that command.

If $stdin is provided, it's supplied to the remote command $cmd on standard input.

NOTE: the SSH-1 protocol does not support running multiple commands per connection, unless those commands are chained together so that the remote shell can evaluate them. Because of this, a new socket connection is created each time you call cmd, and disposed of afterwards. In other words, this code:

    my $ssh = Net::SSH::Perl->new("host1");
    $ssh->login("user1", "pass1");

    $ssh->cmd("foo");
    $ssh->cmd("bar");

will actually connect to the sshd on the first invocation of cmd, then disconnect; then connect again on the second invocation of cmd, then disconnect again.

Note that this does not apply to the SSH-2 protocol. SSH-2 fully supports running more than one command over the same connection.

  $ssh->shell
Opens up an interactive shell on the remote machine and connects it to your STDIN. This is most effective when used with a pseudo tty; otherwise you won't get a command line prompt, and it won't look much like a shell. For this reason--unless you've specifically declined one--a pty will be requested from the remote machine, even if you haven't set the use_pty argument to new (described above).

This is really only useful in an interactive program.

In addition, you'll probably want to set your terminal to raw input before calling this method. This lets Net::SSH::Perl process each character and send it off to the remote machine, as you type it.

To do so, use Term::ReadKey in your program:

    use Term::ReadKey;
    ReadMode('raw');
    $ssh->shell;
    ReadMode('restore');

In fact, you may want to place the "restore" line in an END block, in case your program exits prior to reaching that line.

If you need an example, take a look at eg/pssh, which uses almost this exact code to implement an ssh shell.

  $ssh->register_handler($packet_type, $subref [, @args ])
Registers an anonymous subroutine handler $subref to handle packets of type $packet_type during the client loop. The subroutine will be called when packets of type $packet_type are received, and in addition to the standard arguments (see below), will receive any additional arguments in @args, if specified.

The client loop is entered after the client has sent a command to the remote server, and after any STDIN data has been sent; it consists of reading packets from the server (STDOUT packets, STDERR packets, etc.) until the server sends the exit status of the command executed remotely. At this point the client exits the client loop and disconnects from the server.

When you call the cmd method, the client loop by default simply sticks STDOUT packets into a scalar variable and returns that value to the caller. It does the same for STDERR packets, and for the process exit status. (See the docs for cmd).

You can, however, override that default behavior, and instead process the data itself as it is sent to the client. You do this by calling the register_handler method and setting up handlers to be called at specific times.

The behavior of the register_handler method differs between the Net::SSH::Perl SSH-1 and SSH-2 implementations. This is so because of the differences between the protocols (all client-server communications in SSH-2 go through the channel mechanism, which means that input packets are processed differently).

•   SSH-1 Protocol

    In the SSH-1 protocol, you should call register_handler with two arguments: a packet type $packet_type and a subroutine reference $subref. Your subroutine will receive as arguments the Net::SSH::Perl::SSH1 object (with an open connection to the ssh3), and a Net::SSH::Perl::Packet object, which represents the packet read from the server. It will also receive any additional arguments @args that you pass to register_handler; this can be used to give your callback functions access to some of your otherwise private variables, if desired. $packet_type should be an integer constant; you can import the list of constants into your namespace by explicitly loading the Net::SSH::Perl::Constants module:

        use Net::SSH::Perl::Constants qw( :msg );

    This will load all of the MSG constants into your namespace so that you can use them when registering the handler. To do that, use this method. For example:

        $ssh->register_handler(SSH_SMSG_STDOUT_DATA, sub {
            my($ssh, $packet) = @_;
            print "I received this: ", $packet->get_str;
        });

    To learn about the methods that you can call on the packet object, take a look at the Net::SSH::Perl::Packet docs, as well as the Net::SSH::Perl::Buffer docs (the get_* and put_* methods).

    Obviously, writing these handlers requires some knowledge of the contents of each packet. For that, read through the SSH RFC, which explains each packet type in detail. There's a get_* method for each datatype that you may need to read from a packet.

    Take a look at eg/remoteinteract.pl for an example of interacting with a remote command through the use of register_handler.

•   SSH-2 Protocol

    In the SSH-2 protocol, you call register_handler with two arguments: a string identifying the type of handler you wish to create, and a subroutine reference. The "string" should be, at this point, either "stdout" or "stderr"; any other string will be silently ignored. "stdout" denotes that you wish to handle STDOUT data sent from the server, and "stderr" that you wish to handle STDERR data.

    Your subroutine reference will be passed two arguments: a Net::SSH::Perl::Channel object that represents the open channel on which the data was sent, and a Net::SSH::Perl::Buffer object containing data read from the server. In addition to these two arguments, the callback will be passed any additional arguments @args that you passed to register_handler; this can be used to give your callback functions to otherwise private variables, if desired.

    This illustrates the two main differences between the SSH-1 and SSH-2 implementations. The first difference is that, as mentioned above, all communication between server and client is done through channels, which are built on top of the main connection between client and server. Multiple channels are multiplexed over the same connection. The second difference is that, in SSH-1, you are processing the actual packets as they come in; in SSH-2, the packets have already been processed somewhat, and their contents stored in buffers--you are processing those buffers.

    The above example (the I received this example) of using register_handler in SSH-1 would look like this in SSH-2:

        $ssh->register_handler("stdout", sub {
            my($channel, $buffer) = @_;
            print "I received this: ", $buffer->bytes;
        });

    As you can see, it's quite similar to the form used in SSH-1, but with a few important differences, due to the differences mentioned above between SSH-1 and SSH-2.

ADVANCED METHODS
Your basic SSH needs will hopefully be met by the methods listed above. If they're not, however, you may want to use some of the additional methods listed here. Some of these are aimed at end-users, while others are probably more useful for actually writing an authentication module, or a cipher, etc.

  $ssh->config
Returns the Net::SSH::Perl::Config object managing the configuration data for this SSH object. This is constructed from data passed in to the constructor new (see above), merged with data read from the user and system configuration files. See the Net::SSH::Perl::Config docs for details on methods you can call on this object (you'll probably be more interested in the get and set methods).

  $ssh->sock
Returns the socket connection to sshd. If your client is not connected, dies.

  $ssh->debug($msg)
If debugging is turned on for this session (see the debug parameter to the new method, above), writes $msg to "STDERR". Otherwise nothing is done.

  $ssh->incoming_data
Incoming data buffer, an object of type Net::SSH::Perl::Buffer. Returns the buffer object.

The idea behind this is that we our socket is non-blocking, so we buffer input and periodically check back to see if we've read a full packet. If we have a full packet, we rip it out of the incoming data buffer and process it, returning it to the caller who presumably asked for it.

This data "belongs" to the underlying packet layer in Net::SSH::Perl::Packet. Unless you really know what you're doing you probably don't want to disturb that data.

  $ssh->session_id
Returns the session ID, which is generated from the server's host and server keys, and from the check bytes that it sends along with the keys. The server may require the session ID to be passed along in other packets, as well (for example, when responding to RSA challenges).

  $packet = $ssh->packet_start($packet_type)
Starts building a new packet of type $packet_type. This is just a handy method for lazy people. Internally it calls Net::SSH::Perl::Packet::new, so take a look at those docs for more details.

SUPPORT
For samples/tutorials, take a look at the scripts in eg/ in the distribution directory.

Please report bugs at: https://github.com/lkinley/Net-SSH-Perl/issues

AUTHOR
Development on V2 by Lance Kinley lkinley@rythmos.com

Previous maintainers were: David Robins, dbrobins@cpan.org Dave Rolsky, autarch@urth.org.

Originally written by Benjamin Trott.

COPYRIGHT
Copyright (c) 2015-2017 Rythmos, Inc. Copyright (c) 2001-2003 Benjamin Trott, Copyright (c) 2003-2008 David Rolsky. Copyright (c) David Robins. All rights reserved. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.

The full text of the license can be found in the LICENSE file included with this module.