# Configuration

Paramiko does not itself leverage OpenSSH-style config file directives, but it does implement a parser for the format, which users can honor themselves (and is used by higher-level libraries, such as Fabric).

The API for this is `SSHConfig`, which loads SSH config files from disk, file-like object, or string and exposes a “look up a hostname, get a dict of applicable keywords/values back” functionality.

As with OpenSSH’s own support, this dict will contain values from across the parsed file, depending on the order in which keywords were encountered and how specific or generic the `Host` or `Match` directives were.

## Keywords currently supported

The following is an alphabetical list of which ssh_config directives Paramiko interprets during the parse/lookup process (as above, actual SSH connections do not reference parsed configs). Departures from OpenSSH’s implementation (e.g. to support backwards compat with older Paramiko releases) are included. A keyword by itself means no known departures.

- `AddressFamily`: used when looking up the local hostname for purposes of expanding the `%l`/`%L` tokens (this is actually a minor value-add on top of OpenSSH, which doesn’t actually honor this setting when expanding `%l`).

- `CanonicalDomains`

  > New in version 2.7.

- `CanonicalizeFallbackLocal`: when `no`, triggers raising of `CouldNotCanonicalize` for target hostnames which do not successfully canonicalize.

  > New in version 2.7.

- `CanonicalizeHostname`: along with the other `Canonicaliz*` settings (sans `CanonicalizePermittedCNAMEs`, which is not yet implemented), enables hostname canonicalization, insofar as calling `SSHConfig.lookup` with a given hostname will return a canonicalized copy of the config data, including an updated `HostName` value.

  > New in version 2.7.

- `CanonicalizeMaxDots`

  > New in version 2.7.

- `Host`

- `HostName`: used in `%h` token expansion

- `Match`: supports the keywords `all`, `canonical`, `exec`, `final`, `host`, `localuser`, `originalhost`, and `user`, with the following caveats:

  > - You must have the optional dependency Invoke installed; see the installation docs (in brief: install `paramiko[invoke]` or `paramiko[all]`).

  > - As usual, connection-time information is not present during config lookup, and thus cannot be used to determine matching. This primarily impacts `Match user`, which can match against loaded `User` values but has no knowledge about connection-time usernames.

  > New in version 2.7.

  > Changed in version 3.3: Added support for the `final` keyword.

- `Port`: supplies potential values for `%p` token expansion.

- `ProxyCommand`: see our `ProxyCommand` class for an easy way to honor this keyword from a config you’ve parsed.

  > - Honors token expansion.

  > - When a lookup would result in an effective `ProxyCommand none`, Paramiko (as of 1.x-2.x) strips it from the resulting dict entirely. A later major version may retain the `"none"` marker for clarity’s sake.

- `User`: supplies potential values for `%u` token expansion.

### Expansion tokens

We support most SSH config expansion tokens where possible, so when they are present in a config file source, the result of a `SSHConfig.lookup` will contain the expansions/substitutions (based on the rest of the config or properties of the local system).

Specifically, we are known to support the below, where applicable (e.g. as in OpenSSH, `%L` works in `ControlPath` but not elsewhere):

- `%C`

- `%d`

- `%h`

- `%l`

- `%L`

- `%n`

- `%p`

- `%r`

- `%u`: substitutes the configured `User` value, or the local user (as seen by `getpass.getuser`) if not specified.

In addition, we extend OpenSSH’s tokens as follows:

- `~` is treated like `%d` (expands to the local user’s home directory path) when expanding `ProxyCommand` values, since `ProxyCommand` does not natively support `%d` for some reason.

## `config` module API documentation

Mostly of interest to contributors; see previous section for behavioral details.

Configuration file (aka `ssh_config`) support.

class paramiko.config.SSHConfig

  Representation of config information as stored in the format used by OpenSSH. Queries can be made via `lookup`. The format is described in OpenSSH’s `ssh_config` man page. This class is provided primarily as a convenience to posix users (since the OpenSSH format is a de-facto standard on posix) but should work fine on Windows too.

  New in version 1.6.

  __init__()

    Create a new OpenSSH config object.

    Note: the newer alternate constructors `from_path`, `from_file` and `from_text` are simpler to use, as they parse on instantiation. For example, instead of:

        config = SSHConfig()
        config.parse(open("some-path.config")

    you could:

        config = SSHConfig.from_file(open("some-path.config"))
        # Or more directly:
        config = SSHConfig.from_path("some-path.config")
        # Or if you have arbitrary ssh_config text from some other source:
        config = SSHConfig.from_text("Host foo\n\tUser bar")

  classmethod from_text(text)

    Create a new, parsed `SSHConfig` from `text` string.

    New in version 2.7.

  classmethod from_path(path)

    Create a new, parsed `SSHConfig` from the file found at `path`.

    New in version 2.7.

  classmethod from_file(flo)

    Create a new, parsed `SSHConfig` from file-like object `flo`.

    New in version 2.7.

  parse(file_obj)

    Read an OpenSSH config from the given file object.

    Parameters

      file_obj – a file-like object to read the config file from

  lookup(hostname)

    Return a dict (`SSHConfigDict`) of config options for a given hostname.

    The host-matching rules of OpenSSH’s `ssh_config` man page are used: For each parameter, the first obtained value will be used. The configuration files contain sections separated by `Host` and/or `Match` specifications, and that section is only applied for hosts which match the given patterns or keywords

    Since the first obtained value for each parameter is used, more host- specific declarations should be given near the beginning of the file, and general defaults at the end.

    The keys in the returned dict are all normalized to lowercase (look for `"port"`, not `"Port"`. The values are processed according to the rules for substitution variable expansion in `ssh_config`.

    Finally, please see the docs for `SSHConfigDict` for deeper info on features such as optional type conversion methods, e.g.:

        conf = my_config.lookup('myhost')
        assert conf['passwordauthentication'] == 'yes'
        assert conf.as_bool('passwordauthentication') is True

    Note

    If there is no explicitly configured `HostName` value, it will be set to the being-looked-up hostname, which is as close as we can get to OpenSSH’s behavior around that particular option.

    Parameters

      hostname (str) – the hostname to lookup

    Changed in version 2.5: Returns `SSHConfigDict` objects instead of dict literals.

    Changed in version 2.7: Added canonicalization support.

    Changed in version 2.7: Added `Match` support.

    Changed in version 3.3: Added `Match final` support.

  canonicalize(hostname, options, domains)

    Return canonicalized version of `hostname`.

    Parameters

      - hostname (str) – Target hostname.

      - options – An `SSHConfigDict` from a previous lookup pass.

      - domains – List of domains (e.g. `["paramiko.org"]`).

    Returns

      A canonicalized hostname if one was found, else `None`.

    New in version 2.7.

  get_hostnames()

    Return the set of literal hostnames defined in the SSH config (both explicit hostnames and wildcard entries).

  __weakref__

    list of weak references to the object (if defined)

class paramiko.config.LazyFqdn(config, host=None)

  Returns the host’s fqdn on request as string.

  __init__(config, host=None)
  __str__()

    Return str(self).

  __weakref__

    list of weak references to the object (if defined)

class paramiko.config.SSHConfigDict

  A dictionary wrapper/subclass for per-host configuration structures.

  This class introduces some usage niceties for consumers of `SSHConfig`, specifically around the issue of variable type conversions: normal value access yields strings, but there are now methods such as `as_bool` and `as_int` that yield casted values instead.

  For example, given the following `ssh_config` file snippet:

      Host foo.example.com
          PasswordAuthentication no
          Compression yes
          ServerAliveInterval 60

  the following code highlights how you can access the raw strings as well as usefully Python type-casted versions (recalling that keys are all normalized to lowercase first):

      my_config = SSHConfig()
      my_config.parse(open('~/.ssh/config'))
      conf = my_config.lookup('foo.example.com')

      assert conf['passwordauthentication'] == 'no'
      assert conf.as_bool('passwordauthentication') is False
      assert conf['compression'] == 'yes'
      assert conf.as_bool('compression') is True
      assert conf['serveraliveinterval'] == '60'
      assert conf.as_int('serveraliveinterval') == 60

  New in version 2.5.

  as_bool(key)

    Express given key’s value as a boolean type.

    Typically, this is used for `ssh_config`’s pseudo-boolean values which are either `"yes"` or `"no"`. In such cases, `"yes"` yields `True` and any other value becomes `False`.

    Note

    If (for whatever reason) the stored value is already boolean in nature, it’s simply returned.

    New in version 2.5.

  __weakref__

    list of weak references to the object (if defined)

  as_int(key)

    Express given key’s value as an integer, if possible.

    This method will raise `ValueError` or similar if the value is not int-appropriate, same as the builtin `int` type.

    New in version 2.5.