java通过ssh2协议执行远程shell脚本(ganymed-ssh2-build210.jar)(Java performs a remote shell script (ganymed-ssh2-build210.jar) through the SSH2 protocol)
java通过ssh2协议执行远程shell脚本(ganymed-ssh2-build210.jar)(Java performs a remote shell script (ganymed-ssh2-build210.jar) through the SSH2 protocol)
OpenSession (). Remember to close it after use
=================================================================================================
Excerpt part of the source code is as follows:
Import java.io.BufferedReader;
Import java.io.IOException;
Import java.io.InputStream;
Import java.io.InputStreamReader;
Import org.apache.log4j.Logger;
Import ch.ethz.ssh2.Connection;
Import ch.ethz.ssh2.SCPClient;
Import ch.ethz.ssh2.Session;
Import ch.ethz.ssh2.StreamGobbler;
Public, class, CommandRunner {
Private, static, final, Logger, logger = Logger.getLogger (CommandRunner.class);
Take / documents from other computer network
Public, static, void, scpGet (String, host, String, username, String, password),
String, remoteFile, String, localDir) throws IOException {
If (logger.isDebugEnabled ()) {
Logger.debug ("SPC" ["+ remoteFile +"] from + host + "to""
+ localDir);
}
Connection conn = getOpenedConnection (host, username, password);
SCPClient client = new SCPClient (conn);
Client.get (remoteFile, localDir);
Conn.close ();
}
/ / copy files to the other computer
Public, static, void, scpPut (String, host, String, username, String, password),
String, localFile, String, remoteDir) throws IOException {
If (logger.isDebugEnabled ()) {
Logger.debug ("SPC" ["+ localFile +"] to + host + remoteDir);
}
Connection conn = getOpenedConnection (host, username, password);
SCPClient client = new SCPClient (conn);
Client.put (localFile, remoteDir);
Conn.close ();
}
/ / execute SSH commands.
Public, static, int, runSSH (String, host, String, username, String, password),
String, CMD) throws IOException {
If (logger.isDebugEnabled ()) {
Logger.debug ("running SSH CMD" ["+ CMD +"]);
}
Connection conn = getOpenedConnection (host, username, password);
Session sess = conn.openSession ();
Sess.execCommand (CMD);
InputStream stdout = new StreamGobbler (sess.g