Net::SSH Manual :: Chapter 2: Starting a Session

Net::SSH— Secure Shell for Ruby | Net::SSH Version: 1.1.2 Manual Last Updated: 2007-06-18 18:12 UTC

| Previous (1. Introduction) | Up | Next (3. Channels) # 2. Starting a Session ## 2.1. Using Net::SSH.start Before you can do anything with Net::SSH, you need to require the `net/ssh` module: Requiring Net::SSH [ruby]
    require 'net/ssh'
Once you have required the `net/ssh` module, you can begin an SSH session by calling `Net::SSH.start`. This may be used in one of two ways. If called without a block, it will return a reference to the new session as an instance of a `Net::SSH::Session`. Used this way, you must explicitly close the session when you are finished with it. Opening an SSH session [ruby]
1 2 3 |
    session = Net::SSH.start( 'host', 'user', 'passwd' )
    ...
    session.close
The other approach involves attaching a block to the start method. When used this way, the new session is passed to the block, and the session is automatically closed when the block exits. Opening a transactional SSH session [ruby]
1 2 3 |
    Net::SSH.start( 'host', 'user', 'passwd' ) do |session|
      ...
    end
If you need to specify a different port on the host to connect to (the default is 22), you can specify it immediately after the `host` parameter, like so: Specifying the SSH port [ruby]
1 2 3 |
    Net::SSH.start( 'host', 1234, 'user', 'passwd' ) do |session|
      ...
    end
### Using Keyword Arguments Some people prefer using keyword arguments for functions with more than a couple of parameters. The `start` method supports this approach as well, although the `host` parameter is always positional and always comes first. Using keyword arguments [ruby]
1 2 3 4 5 6 7 |
    Net::SSH.start( 'host',
                    :password=>'passwd',
                    :port=>1234,
                    :username=>'user',
           ... ) do |session|
      ...
    end
(More about the “`...`” stuff, later.) ### Failed Authentication If the username and/or password given to `start` are incorrect, authentication will fail. If authentication fails, a `Net::SSH::AuthenticationFailed` exception will be raised. ## 2.2. Using a Public/Private Key Just as with the OpenSSH version of the `ssh` utilities, Net::SSH supports authentication using public/private keys. ### I don’t know what public/private keys are… Explain, please? Public key/private key encryption is just one way of hiding information from prying eyes. The idea is that you have two tokens: a public key, and a private key. The private key is yours alone—you never let anyone else see it. The public key, on the other hand, is distributable. You give it to anyone that you want to be able to communicate with you securely. The remote party uses your public key to encrypt information. Anything encrypted with your public key may only be decrypted with the corresponding private key, and since you have the only copy of that, you can rest easily knowing that no one can easily intercept your communications! Net::SSH allows you to define a private key, which it will then attempt to use during authentication with the remote server. If the remote server has a copy of the corresponding public key, you will be able to log into that remote server without having to specify a password. Not only is this convenient, but for Ruby scripts, it is much more secure, since you don’t have to hard-code your password in your script. ### Setting up public/private keys Net::SSH, by default, will use the private keys that you have set up for use with ssh. These keys are called “id_dsa” and “id_rsa”, and are located under your home directory, either in a ”.ssh” subdirectory, or a ”.ssh2” subdirectory. The “id_dsa” key is the preferred key (since it uses the stronger DSA encryption), but both DSA and RSA are supported. To create these keys, you can use the “ssh-keygen” utility from OpenSSH. Alternatively, if you have the Net::SSH::Utilities package installed, you can use the “rb-keygen” utility (which is a pure-Ruby implementation of most of the functionality of ssh-keygen). Generating an SSH key [shell]
    ssh-keygen -t dsa
(If you would rather use an RSA key, replace “dsa” with “rsa” in the command given above.) Accept all the defaults when prompted. You will also be asked for a passphrase. This passphrase is an additional level of protection, which prevents anyone from being able to use your private key without knowing the passphrase. Unfortunately, it also means that you have to enter the passphrase every time you use your key. It is up to you what price you want to pay for security, but if you can leave the passphrase blank. In this case, anyone that has a copy of your private key can use it, but it’s a little more convenient to deal with. Once you create your keys, you then need to set up your account on each remote server so that it knows about your public key. To do this, log into the remote server and edit (or create) the file (in your home directory) ”.ssh/authorized_keys”. Just copy the contents of your public key (in your local machine’s home directory, called ”.ssh/id_dsa.pub” or ”.ssh/id_rsa.pub”) into the “authorized_keys” file on a line of its own. Then save the file and logout. Everything should now be set up. (Note: if you have an SSH client installed, it will typically have its own key generation utility. You can use that instead, if you prefer.) ### Connecting using public/private keys Public/private keys are always tried before the explicit password authentication, even if you provide a password. Thus, if you only want to use public/private key authentication, simply remove the password from the argument list. If you can successfully obtain a session handle, then your keys are set up correctly! SSH authentication using keys [ruby]
1 2 3 |
    Net::SSH.start( 'host', 'user' ) do |session|
      ...
    end
Furthermore, if your `USER` environment variable is set to the username that you want to log into the remote machine as, you can even leave the `username` parameter off: Authentication with an implicit user name [ruby]
1 2 3 |
    Net::SSH.start( 'host' ) do |session|
      ...
    end
### Using keys with passphrases When you use a private key that was created with a passphrase, you will be prompted to enter the passphrase when the key is loaded. This may make such a key inappropriate for use in automated environments, but it is certainly more secure than the use of unprotected private keys. ### Using an SSH agent Most SSH clients come with what is called an agent. This is a program that is continually running, and which keeps track of all of a user’s keys. When an SSH client needs to perform an operation using one of the user’s keys, it requests the operation via the agent, rather than performing the operation itself directly with a key. The benefit of this is what is known as single sign-on. If any of your keys have a passphrase, this allows you to enter the passphrase once (when the key is loaded by the agent), and then any SSH program you use will never prompt you for that passphrase again. Net::SSH includes support for interfacing with an SSH agent. This includes support for the PuTTY agent on Windows systems. On Unixish systems, you allow your Net::SSH programs to interface with a running agent by making sure that the `SSH_AGENT_SOCK` environment variable is set to the location of the Unix domain socket that the agent is listening to. Also, make sure you have added all of your keys to the agent (typically by running the `ssh-add` utility. On Windows, the pageant process will be detected automatically, if it is running. A future version of Net::SSH may include it’s own agent implementation as well, to make using an agent on a variety of platforms simpler. Agent forwarding is available, and may be requested with the :forward_agent option to Net::SSH.start. Agents are not forwarded by default. ## 2.3. Options There are various additional options that you can specify when connecting. These options allow you to specify such things as the cipher algorithm to use, whether or not the data stream will be compressed, or explicit paths to the private keys to use. Options are specified as a hash in the last parameter to the `start` method. If using the keyword parameters version of the `start` method, the options hash is whatever is left after processing the `:username`, `:password`, and `:port` options. The complete list of available options, and their valid values, is given in the following table.
Option | Description
--- | ---
`:auth_methods` | This is the list of authorization methods to try. It defaults to “publickey”, “hostbased”, “password”, and “keyboard-interactive”. (These are also the only authorization methods that are supported.) If you want them to be tried in a different order, or if you don’t want certain methods to be used, you can specify your own list via this option.
`:compression` | The compression algorithm to use when compressing the data stream. Valid values are `none` and `zlib`. The default is `none`.
`:compression_level` | This is only used when the compression algorithm is `zlib`. It is an integer value from 0 to 9, representing the quality of the compression. A 0 is no compression, and a 9 is most compression. The default is 6.
`:container` | This is the dependency injection container to use when registering all of the services that Net::SSH uses internally. If unspecified (the default) a new container will be created. This option allows you to reuse a single container for multiple application components.
`:crypto_backend` | This is the cryptography backend to use. It defaults to `:ossl`, which specifies the OpenSSL cryptography engine. Currently, this is the only supported backend, but in the future others may be provided, and this is how they would be selected.
`:encryption` | This is the cipher algorithm to use when sending/receiving data to/from the remote server. It defaults to `3des-cbc`. Other valid algorithms supported by Net::SSH are `aes128-cbc`, `blowfish-cbc`, `aes256-cbc`, `aes192-cbc`, `idea-cbc`, and `none`. Note that the values you specify here are only suggestions, and if the server you are contacting cannot use your recommended algorithm, a fallback algorithm will be used (typically chosen in the order the algorithms were listed, above). This option may take an array, if you want to specify the order of the fallback algorithms to try, as well.
`:forward_agent` | Set to a true value to request that the local authentication agent be forwarded to the remote host. By default the agent will not be forwarded.
`:hmac` | This specifies the “message authentication code” (MAC) algorithm to use to ensure that each packet transmitted and recieved is authentic. This defaults to `hmac-md5`. Other valid algorithms supported by Net::SSH are `hmac-sha1`, `hmac-md5-96`, `hmac-md5-sha1`, and `none`. Note that the values you specify here are only suggestions, and if the server you are contacting cannot use your recommended algorithm, a fallback algorithm will be used (typically chosen in the order the algorithms were listed, above). This option may take an array, if you want to specify the order of the fallback algorithms to try, as well.
`:host_key` | This specifies the host key type that should be used when negotiating keys with the server. This defaults to `ssh-dss`, but may also be `ssh-rsa`. As with some other option types, the value you specify is only a recommendation, not a commandment, and if the server cannot honor the key type you specified, a fallback will be chosen from among the other supported types. If you wish to specify the fallback algorithms to try, you may pass an array as the value of this option, which contains (in order) the key types to try.
`:host_keys` | This is an array of file names that contain the private keys which identify the host your script is running on. These default to `/etc/ssh/ssh_host_dsa_key` and `/etc/ssh/ssh_host_rsa_key` (which are both typically only readable by root). These keys are only used in hostbased authentication.
`:kex` | This specifies the “key-exchange” (KEX) algorithm to use when exchanging keys. Two algorithms are currently supported: `diffie-hellman-group-exchange-sha1`, and `diffie-hellman-group1-sha1`. The default is `diffie-hellman-group-exchange-sha1`.
`:keys` | This specifies the list of private key files to use instead of the defaults (`$HOME/.ssh/id_dsa`, `$HOME/.ssh2/id_dsa`, `$HOME/.ssh/id_rsa`, and `$HOME/.ssh2/id_rsa`). The value of this option should be an array of strings.
`:languages` | This option specifies the preferred language (or languages) that should be used when communicating error messages. It has no effect on Net::SSH, but may cause the server (if it supports your suggested language) to send errors in the language you request. The default is empty.
`:log` | Specifies either a string or an IO object. If it is a string, it names the file that all log messages should be written to. Otherwise, the messages will be written to the IO object directly. Defaults to STDERR.
`:paranoid` | Controls how Net::SSH responds to a server key that it does not recognize. The default, `true`, will result in all keys being accepted the first time they are seen for a particular host, and then an exception being raised if the key ever changes. However, no host key verification will be done if the connection appears to be tunneled over a locally forwarded port. If set to `false`, no server key verification is done. You can also set this to `:very`, in which case errors are raised even if the connection appears to be tunneled.
`:port` | This is the port number that should be used to connect to the remote machine. If you wish to specify the port, you are generally better off specifying it as the second parameter to `start`, rather than as an option, but you can specify it this way, if you prefer.
`:registry_options` | If the `:container` option is not specified, a new container will be created. This option specifies a hash of additional options that may be used to configure the new container (registry). By default, it is empty.
`:verbose` | Specifies how verbose the logging should be. Valid values are `:fatal`, `:error`, `:warn`, `:info`, and `:debug`. Defaults to `:warn`. WARNING: selecting `:debug` will result in LOTS of output! (Further customization of verbosity can be accomplished by specifying which Net::SSH components should have which logging levels, via the `:registry_options` option.)
For example, the following code snippet will connect to the given remote host, and requests that the `ssh-rsa` host key type be used, with the `blowfish-cbc` cipher algorithm, and requests that the given private key file be used. Also, the data stream will be compressed. Specifying options when connecting [ruby]
1 2 3 4 5 6 7 8 9 10 11 12 |
    require 'net/ssh'
    require 'logger'

    Net::SSH.start(
      'host', 'user',
      :host_key => "ssh-rsa",
      :encryption => "blowfish-cbc",
      :keys => [ "/tmp/temporary-key" ],
      :compression => "zlib"
    ) do |session|
      ...
    end
## 2.4. Using Net::SSH::Session Alternatively, you can use `Net::SSH::Session` to start your SSH sessions. The `Net::SSH.start` interface described above is simply a convenience for creating a new Session object explicitly. Using Net::SSH::Session [ruby]
1 2 3 4 5 6 7 8 |
    require 'net/ssh'

    Net::SSH::Session.new(
      'host', 'username', 'password',
      :compression => "zlib"
    ) do |session|
      ...
    end
Note that `Net::SSH::Session#new` accepts the same parameters as Net::SSH.start, and may also be called without a block. Previous (1. Introduction) | Up | Next (3. Channels)