Jonathan Perel

Executing SSH commands

9 posts in this topic

Here's some code I put together using the Ganymed SSH java library and examples to execute SSH commands using ScriptMaster. Its easier than doing SSH calls from RunShellScript. I'm sure there's improvements to be made. 

 

Cheers,

JP

// SSHCommand ( hostname ; privateKey ; username ; command )
// Uses Commons-Io-2.4.jar
// Uses Commons-Lang-2.6.jar
// Uses Ganymed-Ssh2-261.jar

import java.io.IOException;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;

import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;

final String stdout = new String();
final String stderr = new String();


try {

// Convert private key to character array
char[] privateKeyArray = privateKey.toCharArray();

// Create and open connection
Connection theConnection = new Connection(hostname);
theConnection.connect();

// Authenticate with public (private really) key
boolean isSuccess = theConnection.authenticateWithPublicKey(username, privateKeyArray, null);
if (isSuccess == false)
throw new RuntimeException( "ERROR: Authentication error" );

// Open seession and execute command
final Session theSession = theConnection.openSession();
theSession.execCommand(command);

// Get stdout stream and convert to string
final InputStream stdoutStream = new StreamGobbler(theSession.getStdout());
final InputStream stderrStream = new StreamGobbler(theSession.getStderr());

stdout = IOUtils.toString(stdoutStream, "UTF-8");
stderr = IOUtils.toString(stderrStream, "UTF-8");

// Close streams
stdoutStream.close();
stderrStream.close();

// Close the session and connection
theSession.close();
theConnection.close();   

if (StringUtils.isNotEmpty(stderr))
throw new RuntimeException( stderr );

// Return the string
return stdout;
}
catch (IOException e) {
throw new RuntimeException( e );
}
1 person likes this

Share this post


Link to post
Share on other sites

*Changed to using the more updated Orion/Trilead SSH2 libraries. 

http://sourceforge.net/apps/mediawiki/orion-ssh2/index.php

 

Change:

import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;

To:

import com.trilead.ssh2.Connection;
import com.trilead.ssh2.Session;
import com.trilead.ssh2.StreamGobbler;

Share this post


Link to post
Share on other sites

BTW: Requires commons.io and commons.lang JARs as well...

Share this post


Link to post
Share on other sites

Some small improvements making it more Groovy, less Java. Groovy overloads the methods so can be less verbose..

 

StringUtils not needed as if (stderr) is the same as if (StringUtils.isNotEmpty(stderr)) and saves loading another jar just for that one line

No need for import java.io.IOException as that comes for free with Groovy - just makes the code cleaner..

import org.apache.commons.io.IOUtils
//import org.apache.commons.lang.StringUtils

import com.trilead.ssh2.Connection
import com.trilead.ssh2.Session
import com.trilead.ssh2.StreamGobbler

stdout = ''
stderr = ''

try {

// Convert private key to character array
char[] privateKeyArray = privateKey.toCharArray()

// Create and open connection
theConnection = new Connection(hostname)
theConnection.connect()

// Authenticate with public (private really) key
isSuccess = theConnection.authenticateWithPublicKey(username, privateKeyArray, null)
if (!isSuccess )
throw new RuntimeException( 'ERROR: Authentication error' )

// Open seession and execute command
theSession = theConnection.openSession()
theSession.execCommand(command)

// Get stdout stream and convert to string
stdoutStream = new StreamGobbler(theSession.getStdout())
stderrStream = new StreamGobbler(theSession.getStderr())

stdout = IOUtils.toString(stdoutStream, 'UTF-8')
stderr = IOUtils.toString(stderrStream, 'UTF-8')

// Close streams
stdoutStream.close()
stderrStream.close()

// Close the session and connection
theSession.close()
theConnection.close()   

if (stderr){
throw new RuntimeException( stderr )
}
// Return the string
return stdout
}
// catch any exceptions
catch (e) {
throw new RuntimeException( e )
}
1 person likes this

Share this post


Link to post
Share on other sites

Trying to register this on ScriptMaster and getting the following errors - any ideas?

org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
Script1.groovy: 5: unable to resolve class com.trilead.ssh2.Session
 @ line 5, column 1.
   import com.trilead.ssh2.Session
   ^

Script1.groovy: 1: unable to resolve class org.apache.commons.io.IOUtils
 @ line 1, column 1.
   import org.apache.commons.io.IOUtils
   ^

Script1.groovy: 6: unable to resolve class com.trilead.ssh2.StreamGobbler
 @ line 6, column 1.
   import com.trilead.ssh2.StreamGobbler
   ^

Script1.groovy: 4: unable to resolve class com.trilead.ssh2.Connection
 @ line 4, column 1.
   import com.trilead.ssh2.Connection
   ^

4 errors

Share this post


Link to post
Share on other sites

This is because the jar files needed are not loaded.

If you are using the 360works sample file you need to download the gannymead jar file and apache commons, add them to the file, and then make sure they are ticked on the jars tab..

If in you own solution then you need to add the files to your file and load them before you can run this function.

Share this post


Link to post
Share on other sites

Hi folks,

I've been searching this for a while - is it generally not possible to execute ssh/scp commands from "runShellScript"?

Working on MacOS X in this case.

In my tests, the module basically works, delivering correct return values on "pwd", "whoami", "date -u", but on certain commands it simply fails. Of course, these are the desperately needed ones...

Also, I cannot execute a shell-script which is marked executable by using it's path as input to the module. To me, it is not transparent what kind of calls will work and which ones will not.

Please fill my gaps...

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now

  • Similar Content

    • By john renfrew
      Is it possible to get access to the fmpro object inside an inner class in code???
      Example
       
      //at head of groovy code class myClass extends HelperClass { def xx = fmpro.evaluate('Get(PersistentID)') def ... def ... }  
      Currently fails with groovy.lang.MissingPropertyException: No such property: fmpro for class: myClass
    • By truelifeajf
      I'm at a loss as to why I'm getting "ERROR" when:
      I have an image (JPG) 3648 x 5472 pixels at this location:
      $crop_location = /Volumes/Macintosh HD/Applications/Wolf Spring/Wolf Spring Lightroom/Originals/Anderson_Austin_RB6649233682XA-O9330018750AV-crop.JPG
      The file location is definitely correct.
      This function:
      CropImage( $crop_location ; 0 ; 300 ; 3648 ; 5172 )
      Should simply crop 300 pixels off the top, right?
      I get "ERROR"
      Any ideas?
    • By john renfrew
      Once again, but now with more urgency, please can you indicate a timeframe for updating ScriptMaster to be able to use later versions of Java on the Mac.
      There is a completely brand new version of iText (in readiness for PDF 2.0) which has a whole new set of libraries, the code I use needs rewriting in some places, but more importantly is giving MajorMinor version errors as soon as I write my first line of code.
      I already have several functions I can not move but this is somewhat of a killer for me, given that is it my specialist subject...
      This has been rumbling on for too long without any clear help from 360Works.
       
      john
    • By Bilbo
      Hi,
      I have a little problem to run a Merge PDF with the new version of scriptmaster (4.42) and iText 5.5.5 on a Filemaker Pro 14.05 adv on windows 7.
      With this 4.32 version it works: https://dl.dropboxusercontent.com/u/30717534/M4.32.fmp12
      However with this new version 4.42, the Merge PDF script fails: https://dl.dropboxusercontent.com/u/30717534/M4.42.fmp12
      I have tried to get help on another forum, but unfortunately for the moment we didn't found the solution. We arrived at the conclusion that it must be something by my side, but I cannot figure out what is the problem, as I tried on 3 different computers.
      Could anybody try my files on a windows platform please and give me feedback please?
      Does anybody have an idea how to fix it?
      Thanks a lot
    • By MBeck65
      Hello,
      I'm a ScriptMaster Advanced Edition user (I subscribed it during last January) and I have a problem with the registration of a plugin that I created for my environment.
      I describe my environment by hoping that you can support me to solve the problem that I have:
      1. I'm using ScriptMaster on a Mac system (Yosemite) on which both FileMaker Advanced Pro 13.09 and FileMaker Server 13.09 are installed.
      2. I developed and tested with ScriptMaster some functions that I included inside a plugin and I created it with the name myPlugin on my Mac.
      3. I have put the produced plugin myPlugin.fmplugin in the 2 directory that I use in my FileMaker environment, I mean: 
               - HD1/FileMaker Server/Database/Extensions
               - HD1/FileMaker Server/Web Publishing/publishing-engine/cwpc/Plugins
      4. I opened a FileMaker file that uses the functions of my plugin and I registed the plugin on FileMaker Pro Advanced by using the key created by ScriptMaster at the end of the plugin creation.
      5. I deployed my FileMaker file on the FileMaker Server and I work with it so that one of the functions inside the plugin is invoked. The function worked as good as expected but... inside the 360Plugins_ServerScripting64.log file I see the following info:
      INFO: Registered successfully with demo license; will run for two hours after launch.
      And infact it's so: after two hours the plugin stops to work and I'm not more able to use my functions...
      I suppose there's something wrong in the procedure that I follow to register my plugin or, maybe, there's something wrong in my machine environment... I don't know... But I can't work... Could you please help me to understand how to solve this problem?
      Thanks a lot for your support.
       
      Massimo Becattini