Tuesday, 27 September 2016

Executing Remote Admin Tasks with Robot Framework's SSH Library

Technical testing or devops in general often requires administrative tasks to be done at test environments or remote systems under test as part of the testing process. Transferring test data files, cleaning up test server environment or restoring test database are examples of such tasks. Recurring admin tasks naturally are good candidates to be automated.
There are certainly various ways to execute commands and scripts at remote machine and in this example the objective is to keep execution and verification of results at Robot Framework code level, under single flow of control. Alternatively Run commands from OperatingSystem library could be used to launch local scripts taking care of the remote actions or Java or Python code could be run by keywords implemented as a custom test library.
Method demonstrated here is to use Robot Framework’s SSH Library to execute commands/scripts at remote machine and read the results to be asserted. I have two examples, firstly a single command executing a remote script expected to return with code 0. The second example deals with executing a sequence of remote commands as well as reading the results from output.
See SSH Library documentation for installation instructions. By using pip the required dependencies are also installed and the keywords are usable from Robot FW code after importing the SSHLibrary itself. 

Note that by default Execute Command returns the stdout output. To get the return code instead, we explicitly set both return_rc argument as True and return_stdout as False.
Commands run by Execute Command or Start Command keywords are always run in a new shell and hence the changes (for example cd command) made by previous keywords are not visible to the next keywords when executing multiple commands. To execute a sequence of commands at a remote shell we use Write and Read keywords as in the following example. Assume an asynchronous/background process is started and we want to wait until expected indication about the completion of the task can be read from output, for example ”Result = OK.” or ”Result = FAIL.” written by the custom script in this example. Output is read until ”Result =” can be read from the output and then read until a dot character to get the result string for assertion. Note that this should happen within the timeout set when importing the SSH Library, 10 minutes in this example.

A bit of string manipulation is done here with Strip String and Fetch From Left keywords to get the exact string representing the result. See also related keywords Read, Read Until Prompt and Read Until Regexp to find the most suitable one depending on the expected output.