Of course, one can forgo the 1.0 document and calling parseGroovyFromPage(),
and just put the class directly inside one's 2.0 groovy script and call new
SshHelper(). Of course, this still doesn't solve the problem of wanting to
reuse groovy classes across multiple documents, while wanting to use Xwiki
documents for the groovy code for easier development. Thus I still seek a
2.0-compatible version of parseGroovyFromPage('Groovy.SshHelperClass')...
Here's the all-in-one version of the previous
SSH/groovy/run-a-unix-process-out-of-a-webpage example
==== Standalone version of SshHelperTest ====
See also [[HowtoSetupUserTomcatSshSlave]] [[SshHelperTest]] [[
http://blog.asyd.net/2008/12/xwiki-cest-decidemment-magique/]]
{{groovy}}
/* orig [
http://blog.asyd.net/wp-content/uploads/2008/12/sshhelper.groovy]
#* */
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import com.trilead.ssh2.Connection;
import com.trilead.ssh2.Session;
import com.trilead.ssh2.StreamGobbler;
/**
*
* @author asyd, modified by NielsMayer
*/
class SshHelper {
def connection
def session
void openSession(hostname, port, username, identityfile, password) {
def identityIOFile = new File(identityfile)
this.connection = new Connection(hostname, Integer.parseInt(port))
this.connection.connect()
if (!connection.authenticateWithPublicKey(username, identityIOFile,
password)) {
println "Authentication failed!"
}
}
String runCommand(command) {
this.session = connection.openSession()
this.session.execCommand(command)
def stdoutStream = new StreamGobbler(this.session.getStdout())
def stdoutReader = new BufferedReader(new
InputStreamReader(stdoutStream))
def lineout = ""
def stdoutOutput = ""
while ((lineout = stdoutReader.readLine()) != null) {
stdoutOutput += (lineout + "\n")
}
this.session.close()
this.session = null
return stdoutOutput
}
void close() {
if (this.session != null) {
this.session.close()
}
this.connection.close()
}
}
/*
* Using class above, open an SSH connection to tomcat-ssh-slave
* using user tomcat6's private key created via 'ssh-keygen -t dsa'
* while logged in as ~tomcat6
*/
def sshHelper = new SshHelper();
sshHelper.openSession("127.0.0.1", "22",
"tomcat-ssh-slave",
"/usr/share/tomcat6/.ssh/id_dsa", "")
println "==== Output from 'uname -a' ===="
println "##" + sshHelper.runCommand("uname -a") + "##"
println "==== Output from 'free' ===="
println "##" + sshHelper.runCommand("free") + "##"
println "==== Output from 'ps -l U tomcat-ssh-slave U tomcat U apache'
===="
println "##" + sshHelper.runCommand("ps -l h U tomcat-ssh-slave U tomcat U
apache") + "##"
println "==== Output from 'df -H' ===="
println "##" + sshHelper.runCommand("df -H") + "##"
println "==== Output from 'top -b -n 1' ===="
println "##" + sshHelper.runCommand("top -b -n 1") + "##"
println "==== Close the connection and exit tomcat-ssh-slave shell ===="
sshHelper.close()
/* *# */
{{/groovy}}
-- Niels
http://nielsmayer.com