cfme.utils.ssh module

class cfme.utils.ssh.SSHClient(stream_output=False, **connect_kwargs)[source]

Bases: paramiko.client.SSHClient

paramiko.SSHClient wrapper

Allows copying/overriding and use as a context manager Constructor kwargs are handed directly to paramiko.SSHClient.connect()

Parameters
  • container – If specified, then it is assumed that the VM hosts a container of CFME. The param then contains the name of the container.

  • project – openshift’s project which holds CFME pods

  • is_pod – If specified and True, then it is assumed that the target is a podified openshift app and container then specifies the name of the pod to interact with.

  • stdout – If specified, overrides the system stdout file for streaming output.

  • stderr – If specified, overrides the system stderr file for streaming output.

appliance_has_netapp()[source]
client_address()[source]
close()[source]

Close this SSHClient and its underlying .Transport.

Warning

Failure to do this may, in some situations, cause your Python interpreter to hang at shutdown (often due to race conditions). It’s good practice to close your client objects anytime you’re done using them, instead of relying on garbage collection.

connect(hostname=None, **kwargs)[source]

Connect to an SSH server and authenticate to it. The server’s host key is checked against the system host keys (see load_system_host_keys) and any local host keys (load_host_keys). If the server’s hostname is not found in either set of host keys, the missing host key policy is used (see set_missing_host_key_policy). The default policy is to reject the key and raise an .SSHException.

Authentication is attempted in the following order of priority:

  • The pkey or key_filename passed in (if any)

    • key_filename may contain OpenSSH public certificate paths as well as regular private-key paths; when files ending in -cert.pub are found, they are assumed to match a private key, and both components will be loaded. (The private key itself does not need to be listed in key_filename for this to occur - just the certificate.)

  • Any key we can find through an SSH agent

  • Any “id_rsa”, “id_dsa” or “id_ecdsa” key discoverable in ~/.ssh/

    • When OpenSSH-style public certificates exist that match an existing such private key (so e.g. one has id_rsa and id_rsa-cert.pub) the certificate will be loaded alongside the private key and used for authentication.

  • Plain username/password auth, if a password was given

If a private key requires a password to unlock it, and a password is passed in, that password will be used to attempt to unlock the key.

Parameters
  • hostname (str) – the server to connect to

  • port (int) – the server port to connect to

  • username (str) – the username to authenticate as (defaults to the current local username)

  • password (str) – Used for password authentication; is also used for private key decryption if passphrase is not given.

  • passphrase (str) – Used for decrypting private keys.

  • pkey (PKey) – an optional private key to use for authentication

  • key_filename (str) – the filename, or list of filenames, of optional private key(s) and/or certs to try for authentication

  • timeout (float) – an optional timeout (in seconds) for the TCP connect

  • allow_agent (bool) – set to False to disable connecting to the SSH agent

  • look_for_keys (bool) – set to False to disable searching for discoverable private key files in ~/.ssh/

  • compress (bool) – set to True to turn on compression

  • sock (socket) – an open socket or socket-like object (such as a .Channel) to use for communication to the target host

  • gss_auth (bool) – True if you want to use GSS-API authentication

  • gss_kex (bool) – Perform GSS-API Key Exchange and user authentication

  • gss_deleg_creds (bool) – Delegate GSS-API client credentials or not

  • gss_host (str) – The targets name in the kerberos database. default: hostname

  • gss_trust_dns (bool) – Indicates whether or not the DNS is trusted to securely canonicalize the name of the host being connected to (default True).

  • banner_timeout (float) – an optional timeout (in seconds) to wait for the SSH banner to be presented.

  • auth_timeout (float) – an optional timeout (in seconds) to wait for an authentication response.

  • disabled_algorithms (dict) – an optional dict passed directly to .Transport and its keyword argument of the same name.

Raises

.BadHostKeyException – if the server’s host key could not be verified

Raises

.AuthenticationException – if authentication failed

Raises

.SSHException – if there was any other error connecting or establishing an SSH session

Raises

socket.error – if a socket error occurred while connecting

Changed in version 1.15: Added the banner_timeout, gss_auth, gss_kex, gss_deleg_creds and gss_host arguments.

Changed in version 2.3: Added the gss_trust_dns argument.

Changed in version 2.4: Added the passphrase argument.

Changed in version 2.6: Added the disabled_algorithms argument.

property connected
cpu_spike(seconds=60, cpus=2, **kwargs)[source]

Creates a CPU spike of specific length and processes.

Parameters
  • seconds – How long the spike should last.

  • cpus – How many processes to use.

Returns

See SSHClient.run_command()

get_build_date()[source]
get_build_datetime()[source]
get_file(remote_file, local_path='', **kwargs)[source]
get_transport(*args, **kwargs)[source]

Return the underlying .Transport object for this SSH connection. This can be used to perform lower-level tasks, like opening specific kinds of channels.

Returns

the .Transport for this connection

is_appliance_downstream()[source]
property is_container
load_host_keys(filename)[source]

Load host keys from a local host-key file. Host keys read with this method will be checked after keys loaded via load_system_host_keys, but will be saved back by save_host_keys (so they can be modified). The missing host key policy .AutoAddPolicy adds keys to this set and saves them, when connecting to a previously-unknown server.

This method can be called multiple times. Each new set of host keys will be merged with the existing set (new replacing old if there are conflicts). When automatically saving, the last hostname is used.

Parameters

filename (str) – the filename to read

Raises

IOError – if the filename could not be read

load_system_host_keys(filename=None)[source]

Load host keys from a system (read-only) file. Host keys read with this method will not be saved back by save_host_keys.

This method can be called multiple times. Each new set of host keys will be merged with the existing set (new replacing old if there are conflicts).

If filename is left as None, an attempt will be made to read keys from the user’s local “known hosts” file, as used by OpenSSH, and no exception will be raised if the file can’t be read. This is probably only useful on posix.

Parameters

filename (str) – the filename to read, or None

Raises

IOError – if a filename was provided and the file could not be read

open_sftp(*args, **kwargs)[source]

Open an SFTP session on the SSH server.

Returns

a new .SFTPClient session object

patch_file(local_path, remote_path, md5=None)[source]

Patches a single file on the appliance

Parameters
  • local_path – Path to patch (diff) file

  • remote_path – Path to file to be patched (on the appliance)

  • md5 – MD5 checksum of the original file to check if it has changed

Returns

True if changes were applied, False if patching was not necessary

Note

If there is a .bak file present and the file-to-be-patched was not patched by the current patch-file, it will be used to restore it first. Recompiling assets and restarting appropriate services might be required.

put_file(local_file, remote_file='.', **kwargs)[source]
run_command(command, timeout=1200.0, ensure_host=False, ensure_user=False, container=None)[source]

Run a command over SSH.

Parameters
  • command – The command. Supports taking dicts as version picking.

  • timeout – Timeout after which the command execution fails.

  • ensure_host – Ensure that the command is run on the machine with the IP given, not any container or such that we might be using by default.

  • ensure_user – Ensure that the command is run as the user we logged in, so in case we are not root, setting this to True will prevent from running sudo.

  • container – allows to temporarily override default container

Returns

A SSHResult instance.

run_rails_command(command, timeout=1200.0, **kwargs)[source]
run_rails_console(command, sandbox=False, timeout=1200.0)[source]

Runs Ruby inside of rails console. stderr is thrown away right now but could prove useful for future performance analysis of the queries rails runs. The command is encapsulated by double quotes. Sandbox rolls back all changes made to the database if used.

run_rake_command(command, timeout=1200.0, disable_db_check=False, **kwargs)[source]
property status

Parses the output of the systemctl status evmserverd.

Returns

A dictionary containing servers and workers, both lists. Each of the lists contains dictionaries, one per line. You can refer inside the dictionary using the headers.

uptime()[source]
property username
vmdb_version
class cfme.utils.ssh.SSHResult(command, rc, output)[source]

Bases: object

Allows rich comparison for more convenient testing.

Given you have result which is an instance of SSHResult, you can do as follows

assert result  # If $?=0, then the result evaluates to a truthy value and passes the assert
assert result == 'installed'  # direct matching of the output value
assert 'something' in result  # like before but uses the ``in`` matching for a partial match
assert result == 5  # assert that the $?=5 (you can use <, >, ...)

Therefore this class can act like 3 kinds of values

  • Like a string (with the output of the command) when compared with or cast to one

  • Like a number (with the return code) when compared with or cast to one

  • Like a bool, giving truthy value if the return code was zero. That is related to the preceeding bullet.

But it still subclasses the original class therefore all old behaviour is kept. But you don’t have to expand the tuple or pull the value out if you are checking only one of them.

property failed
property success
class cfme.utils.ssh.SSHTail(remote_filename, **connect_kwargs)[source]

Bases: cfme.utils.ssh.SSHClient

lines_as_list()[source]

Return lines as list

raw_lines()[source]
raw_string()[source]
set_initial_file_end()[source]
cfme.utils.ssh.keygen()[source]

Generate temporary ssh keypair for appliance SSH auth

Intended not only to simplify ssh access to appliances, but also to simplify SSH access from one appliance to another in multi-appliance setups

cfme.utils.ssh.wait_for(func, func_args=[], func_kwargs={}, *, logger=<TraceLogger cfme (INFO)>, **kwargs)

Waits for a certain amount of time for an action to complete Designed to wait for a certain length of time, either linearly in 1 second steps, or exponentially, up to a maximum. Returns the output from the function once it completes successfully, along with the time taken to complete the command.

It tries to use time.monotonic(), if it is not present, falls back to time.time(), but it then is not resistant against system time changes.

Note: If using the expo keyword, the returned elapsed time will be inaccurate

as wait_for does not know the exact time that the function returned correctly, only that it returned correctly at last check.

Parameters
  • func – A function to be run

  • func_args – A list of function arguments to be passed to func

  • func_kwargs – A dict of function keyword arguments to be passed to func

  • num_sec – An int describing the number of seconds to wait before timing out.

  • timeout – Either an int describing the number of seconds to wait before timing out. Or a timedelta object. Or a string formatted like 1h 10m 5s. This then sets the num_sec variable.

  • expo – A boolean flag toggling exponential delay growth.

  • message – A string containing a description of func’s operation. If None, defaults to the function’s name.

  • fail_condition – An object describing the failure condition that should be tested against the output of func. If func() == fail_condition, wait_for continues to wait. Can be a callable which takes the result and returns boolean whether to fail. You can also specify it as a set, that way it checks whether it is present in the iterable.

  • handle_exception – A boolean controlling the handling of excepetions during func() invocation. If set to True, in cases where func() results in an exception, clobber the exception and treat it as a fail_condition.

  • delay – An integer describing the number of seconds to delay before trying func() again.

  • fail_func – A function to be run after every unsuccessful attempt to run func()

  • quiet – Do not write time report to the log (default False)

  • very_quiet – Do not log unless there was an error (default False). Implies quiet.

  • silent_failure – Even if the entire attempt times out, don’t throw a exception.

  • log_on_loop – Fire off a log.info message indicating we’re still waiting at each iteration of the wait loop

Returns

A tuple containing the output from func() and a float detailing the total wait time.

Raises

TimedOutError – If num_sec is exceeded after an unsuccessful func() invocation.