SSHLibrary is a Robot Framework test library for SSH and SFTP.

This document explains how to use keywords provided by SSHLibrary. For information about installation, support, and more please visit the project page. For more information about Robot Framework, see http://robotframework.org.

The library has the following main usages:

This library works both with Python and Jython, but uses different SSH modules internally depending on the interpreter. See installation instructions for more details about the dependencies. IronPython is unfortunately not supported. Python 3 is supported starting from SSHLibrary 3.0.0.

Table of contents

Connections and login

SSHLibrary supports multiple connections to different hosts. New connections are opened with Open Connection.

Login into the host is done either with username and password (Login) or with public/private key pair (Login With Public key).

Only one connection can be active at a time. This means that most of the keywords only affect the active connection. Active connection can be changed with Switch Connection.

Configuration

Default settings for all the upcoming connections can be configured on library importing or later with Set Default Configuration.

Using Set Default Configuration does not affect the already open connections. Settings of the current connection can be configured with Set Client Configuration. Settings of another, non-active connection, can be configured by first using Switch Connection and then Set Client Configuration.

Most of the defaults can be overridden per connection by defining them as arguments to Open Connection. Otherwise the defaults are used.

Configurable per connection

Prompt

Argument prompt defines the character sequence used by Read Until Prompt and must be set before that keyword can be used.

If you know the prompt on the remote machine, it is recommended to set it to ease reading output from the server after using Write. In addition to that, Login and Login With Public Key can read the server output more efficiently when the prompt is set.

Prompt can be specified either as a normal string or as a regular expression. The latter is especially useful if the prompt changes as a result of the executed commands. Prompt can be set to be a regular expression by giving the prompt argument a value starting with REGEXP: followed by the actual regular expression like prompt=REGEXP:[$#]. See the Regular expressions section for more details about the syntax.

The support for regular expressions is new in SSHLibrary 3.0.0.

Encoding

Argument encoding defines the character encoding of input and output sequences. The default encoding is UTF-8.

Path separator

Argument path_separator must be set to the one known by the operating system and the SSH server on the remote machine. The path separator is used by keywords Get File, Put File, Get Directory and Put Directory for joining paths correctly on the remote host.

The default path separator is forward slash / which works on Unix-like machines. On Windows the path separator to use depends on the SSH server. Some servers use forward slash and others backslash, and users need to configure the path_separator accordingly. Notice that using a backslash in Robot Framework test data requires doubling it like \\.

The path separator can be configured on library importing or later, using Set Default Configuration, Set Client Configuration and Open Connection.

Timeout

Argument timeout is used by Read Until variants. The default value is 3 seconds. See time format below for supported timeout syntax.

Newline

Argument newline is the line break sequence used by Write keyword and must be set according to the operating system on the remote machine. The default value is LF (same as \n) which is used on Unix-like operating systems. With Windows remote machines, you need to set this to CRLF (\r\n).

Terminal settings

Argument term_type defines the virtual terminal type, and arguments width and height can be used to control its virtual size.

Escape ansi sequneces

Argument escape_ansi is a parameter used in order to escape ansi sequences that appear in the output when the remote machine has Windows as operating system.

Not configurable per connection

Loglevel

Argument loglevel sets the log level used to log the output read by Read, Read Until, Read Until Prompt, Read Until Regexp, Write, Write Until Expected Output, Login and Login With Public Key. The default level is INFO.

loglevel is not configurable per connection but can be overridden by passing it as an argument to the most of the aforementioned keywords. Possible argument values are TRACE, DEBUG, INFO, WARN and NONE (no logging).

Executing commands

For executing commands on the remote machine, there are two possibilities:

  • Execute Command and Start Command. The command is executed in a new shell on the remote machine, which means that possible changes to the environment (e.g. changing working directory, setting environment variables, etc.) are not visible to the subsequent keywords.

Interactive shells

Write, Write Bare, Write Until Expected Output, Read, Read Until, Read Until Prompt and Read Until Regexp can be used to interact with the server within the same shell.

Consumed output

All of these keywords, except Write Bare, consume the read or the written text from the server output before returning. In practice this means that the text is removed from the server output, i.e. subsequent calls to Read keywords do not return text that was already read. This is illustrated by the example below.

Write echo hello # Consumes written echo hello
${stdout}= Read Until hello # Consumes read hello and everything before it
Should Contain ${stdout} hello
${stdout}= Read # Consumes everything available
Should Not Contain ${stdout} hello # hello was already consumed earlier

The consumed text is logged by the keywords and their argument loglevel can be used to override the default log level.

Login and Login With Public Key consume everything on the server output or if the prompt is set, everything until the prompt.

Reading

Read, Read Until, Read Until Prompt and Read Until Regexp can be used to read from the server. The read text is also consumed from the server output.

Read reads everything available on the server output, thus clearing it.

Read Until variants read output up until and including expected text. These keywords will fail if the timeout expires before expected is found.

Writing

Write and Write Until Expected Output consume the written text from the server output while Write Bare does not.

These keywords do not return any output triggered by the written text. To get the output, one of the Read keywords must be explicitly used.

Pattern matching

Glob patterns

Some keywords allow their arguments to be specified as glob patterns where:

* matches anything, even an empty string
? matches any single character
[chars] matches any character inside square brackets (e.g. [abc] matches either a, b or c)
[!chars] matches any character not inside square brackets

Pattern matching is case-sensitive regardless the local or remote operating system. Matching is implemented using Python's fnmatch module.

Regular expressions

Some keywords support pattern matching using regular expressions, which are more powerful but also more complicated than glob patterns. This library uses Python's regular expressions, which are introduced in the Regular Expression HOWTO.

Remember that in Robot Framework data the backslash that is used a lot in regular expressions is an escape character and needs to be doubled to get a literal backslash. For example, \\d\\d\\s matches two digits followed by a whitespace character.

Possible flags altering how the expression is parsed (e.g. re.IGNORECASE, re.MULTILINE) can be set by prefixing the pattern with the (?iLmsux) group. The available flags are IGNORECASE: i, MULTILINE: m, DOTALL: s, VERBOSE: x, UNICODE: u, and LOCALE: L. For example, (?is)pat.ern uses IGNORECASE and DOTALL flags.

Example

*** Settings ***
Documentation          This example demonstrates executing commands on a remote machine
...                    and getting their output and the return code.
...
...                    Notice how connections are handled as part of the suite setup and
...                    teardown. This saves some time when executing several test cases.

Library                SSHLibrary
Suite Setup            Open Connection And Log In
Suite Teardown         Close All Connections

*** Variables ***
${HOST}                localhost
${USERNAME}            test
${PASSWORD}            test

*** Test Cases ***
Execute Command And Verify Output
    [Documentation]    Execute Command can be used to ran commands on the remote machine.
    ...                The keyword returns the standard output by default.
    ${output}=         Execute Command  echo Hello SSHLibrary!
    Should Be Equal    ${output}        Hello SSHLibrary!

Execute Command And Verify Return Code
    [Documentation]    Often getting the return code of the command is enough.
    ...                This behaviour can be adjusted as Execute Command arguments.
    ${rc}=             Execute Command  echo Success guaranteed.    return_stdout=False    return_rc=True
    Should Be Equal    ${rc}            ${0}

Executing Commands In An Interactive Session
    [Documentation]    Execute Command always executes the command in a new shell.
    ...                This means that changes to the environment are not persisted
    ...                between subsequent Execute Command keyword calls.
    ...                Write and Read Until variants can be used to operate in the same shell.
    Write              cd ..
    Write              echo Hello from the parent directory!
    ${output}=         Read Until       directory!
    Should End With    ${output}        Hello from the parent directory!

*** Keywords ***
Open Connection And Log In
   Open Connection     ${HOST}
   Login               ${USERNAME}        ${PASSWORD}

Save the content as file executing_command.txt and run:

robot executing_commands.txt

You may want to override the variables from commandline to try this out on your remote machine:

robot -v HOST:my.server.com -v USERNAME:johndoe -v PASSWORD:secretpasswd executing_commands.txt

Time format

All timeouts, delays or retry intervals can be given as numbers considered seconds (e.g. 0.5 or 42) or in Robot Framework's time syntax (e.g. 1.5 seconds or 1 min 30 s). For more information about the time syntax see the Robot Framework User Guide.

Boolean arguments

Some keywords accept arguments that are handled as Boolean values true or false. If such an argument is given as a string, it is considered false if it is either an empty string or case-insensitively equal to false, none or no. Other strings are considered true regardless their value, and other argument types are tested using the same rules as in Python.

True examples:

List Directory ${path} recursive=True # Strings are generally true.
List Directory ${path} recursive=yes # Same as the above.
List Directory ${path} recursive=${TRUE} # Python True is true.
List Directory ${path} recursive=${42} # Numbers other than 0 are true.

False examples:

List Directory ${path} recursive=False # String false is false.
List Directory ${path} recursive=no # Also string no is false.
List Directory ${path} recursive=${EMPTY} # Empty string is false.
List Directory ${path} recursive=${FALSE} # Python False is false.

Prior to SSHLibrary 3.1.0, all non-empty strings, including no and none were considered to be true. Considering none false is new in Robot Framework 3.0.3.

Transfer files with SCP

Secure Copy Protocol (SCP) is a way of secure transfer of files between hosts. It is based on SSH protocol. The advantage it brings over SFTP is transfer speed. SFTP however can also be used for directory listings and even editing files while transferring. SCP can be enabled on keywords used for file transfer: Get File, Get Directory, Put File, Put Directory by setting the scp value to TRANSFER or ALL.

OFF Transfer is done using SFTP only. This is the default value
TRANSFER Directory listings (needed for logging) will be done using SFTP. Actual file transfer is done with SCP.
ALL Only SCP is used for file transfer. No logging available.

There are some limitations to the current SCP implementation::

  • When using SCP, files cannot be altered during transfer and newline argument does not work.
  • If scp=ALL only source and destination arguments will work on the keywords. The directories are transferred recursively. Also, when running with Jython Put Directory and Get Directory won't work due to current Trilead implementation.
  • If running with Jython you can encounter some encoding issues when transferring files with non-ascii characters.

SCP transfer was introduced in SSHLibrary 3.3.0.

Preserving original times

SCP allows some configuration when transferring files and directories. One of this configuration is whether to preserve the original modify time and access time of transferred files and directories. This is done using the scp_preserve_times argument. This argument works only when scp argument is set to TRANSFER or ALL. When moving directory with scp set to TRANSFER and scp_preserve_times is enabled only the files inside the director will keep their original timestamps. Also, when running with Jython scp_preserve_times won't work due to current current Trilead implementation.

scp_preserve_times was introduced in SSHLibrary 3.6.0.

Aliases

SSHLibrary allows the use of an alias when opening a new connection using the parameter alias.

Open Connection alias=connection1

These aliases can later be used with other keywords like Get Connection or Switch Connection in order to get information respectively to switch to a certain connection that has that alias.

When a connection is closed, it is no longer possible to switch or get information about the other connections that have the same alias as the closed one. If the same alias is used for more connections, keywords Switch Connection and Get Connection will switch/get information only about the last opened connection with that alias.

Open Connection my.server.com alias=conn
Open Connection my.server.com alias=conn
Open Connection my.server.com alias=conn2
${conn_info}= Get Connection conn
Should Be Equal As Integers ${conn_info.index} 2
Switch Connection conn
${current_conn}= Get Connection conn
Should Be Equal As Integers ${current_conn.index} 2

Note that if a connection that has the same alias as other connections is closed trying to switch or get information about the other connections that have the same alias is impossible.

'Open Connection` my.server.com alias=conn
'Open Connection` my.server.com alias=conn
Close Connection
Switch Connection conn
Run Keyword And Expect Error Non-existing index or alias 'conn'. Switch Connection conn