Working with SSH from Sahi
Consider this scenario
- You create a loan from your banking web application
- An xml is created and stored on your web server
- The xml is then consumed by another third party service which you do not have control over (or you are not testing it right now)
In your test case you need to verify if the xml was created properly. Normally you would have created an ssh session via shell or putty and checked the contents of the XML file. This section explains how you can accomplish this via Sahi.
Download the following jars and copy them to sahi/userdata/extlib folder (create extlib if not already present)
- enchanter-core-0.6.jar (Download from http://code.google.com/p/enchanter/)
- ganymed-ssh2-build210.jar (Download http://www.ganymed.ethz.ch/ssh2/ganymed-ssh2-build210.zip, unzip it and copy only ganymed-ssh2-build210.jar)
// Access enchanter
var ssh = new Packages.org.twdata.enchanter.impl.DefaultStreamConnection();
// Connect to your server. change the host, port, username and password
ssh.connect( "myserver.example.com", 7822, "username", "password");
// Wait for the prompt as seen when you connect via putty.
// Here we have used "~$", it may be different for your server
var $prompt = "~$";
ssh.waitFor($prompt);
// Send the command to be executed
ssh.sendLine("ls -al");
java.lang.System.out.println("Done sending");
// Collect the out put till it shows the prompt again
var $i=0;
var $outputAr = [];
while (true) {
var $line = ssh.getLine();
if ($line == null || $prompt == _sahi.trim($line) || $i++ > 100) break;
$outputAr.push($line);
}
var $output = $outputAr.join("\r\n");
// disconnect from the ssh session
ssh.disconnect();
// Use $output
_alert($output);
We are just utilizing a java class here to make the ssh connection. Sahi itself does not do much here, except calling the correct APIs. If you run into any trouble, have a look at the documentation for
enchanter.
To connect using a private key, use something like this:
ssh.connect( "myserver.example.com", 7822, "username", "password", "C:/mykey.pem");
Note that you need to use a .pem key and not .ppk keys as used with putty.
If there is no password, try with null or
""
.
ssh.connect( "myserver.example.com", 7822, "username", null, "C:/mykey.pem");
or
ssh.connect( "myserver.example.com", 7822, "username", "", "C:/mykey.pem");