Java executes remote shell scripts via the SSH2 Protocol (GANYMED-SSH2-BUILD210.JAR)
Use the following steps:
1. Guide Package
Website Download:
http://www.ganymed.ethz.ch/ssh2/
MAVEN Coordinates:
<dependency>
<groupId>com.ganymed.ssh2</groupId>
<artifactId> ganymed-ssh2-build</artifactid>
<version>210</version>
</dependency>
2.apI description
1. First construct a connector, passing in a need to login IP address
Connection conn = new Connection (hostname);
2. Analog Landing destination server incoming username and password,
Boolean isauthenticated = Conn.authenticatewithpassword (username, password); it returns a Boolean value, True represents the successful landing of the destination server, or failed to log in
3. Open a session, a bit like hibernate session, execute the Linux script commands you need.
Session Sess = Conn.opensession ();
Sess.execcommand ("last");
4. Receive the console return results on the target server and read the contents of the BR
InputStream stdout = new Streamgobbler (Sess.getstdout ());
BufferedReader br = new BufferedReader (new InputStreamReader (stdout));
5. Sign of success of script: 0-Success not 0-failure
System.out.println ("ExitCode:" + sess.getexitstatus ());
6. Close session and connection
Sess.close ();
Conn.close ();
Note:
1. After the successful 2nd certification, the current directory is located under the/home/username/directory, you can specify the absolute path of the script file, or through the CD to navigate to the directory where the script file, and then pass the script required to execute the parameters, complete the script call execution.
2. After the execution of the script, you can get the results of the script execution text, the text needs to be correctly encoded and returned to the client, to avoid garbled.
3. If you need to execute more than one Linux console script, such as the return result of the first script is the entry of the second script, you must open multiple sessions, that is, multiple calls
Session Sess = Conn.opensession (), after use, remember to close it.
3. Instance code, this class can directly copy the past
Import Java.io.BufferedReader;
Import java.io.IOException;
Import Java.io.InputStream;
Import Java.io.InputStreamReader;
Import java.io.UnsupportedEncodingException;
Import Org.apache.commons.lang.StringUtils;
Import ch.ethz.ssh2.Connection;
Import ch.ethz.ssh2.Session;
Import Ch.ethz.ssh2.StreamGobbler; /** * Remote Execution Linux shell script * @author Ickes * @since V0.1 * More Highlights: Http://www.bianceng.cnhttp://www.bianceng.cn/P rogramming/java/*/public class Remoteexecutecommand {//character encoding default is utf-8 private static String defaultchart= "U
TF-8 ";
Private Connection Conn;
Private String IP;
Private String UserName;
Private String userpwd;
Public remoteexecutecommand (String IP, String userName, String userpwd) {this.ip = IP;
This.username = UserName;
This.userpwd = userpwd;
Public Remoteexecutecommand () {}/** * Telnet to linux host * @author Ickes * @since V0.1 * @return * Login successfully returns TRUE, otherwise return false * * *
public Boolean login () {Boolean flg=false;
try {conn = new Connection (IP); Conn.connect ();//Connect Flg=conn.authenticatewithpassword (UserName, userpwd);//authentication} catch (IOException
e) {e.printstacktrace ();
return FLG; /** * @author Ickes * Remote execution of SHLL scripts or commands * @param cmd * The command to be executed * @return *
The result value returned after the command was executed * @since V0.1 */public string execute (string cmd) {string result= ""; try {if (login ()) {session session= conn.opensession ();//Open a conversation sessio
N.execcommand (cmd);//execute Command result=processstdout (session.getstdout (), Defaultchart); If NULL for the standard output, the script executes an error if Stringutils.isblank (rEsult)) {result=processstdout (Session.getstderr (), Defaultchart);
} conn.close ();
Session.close ();
} catch (IOException e) {e.printstacktrace ();
return result;
/** * @author Ickes * Remote execution SHLL script or command * @param cmd * command to be executed * @return The result value returned after the command is executed successfully, if the command fails, returns an empty string, NOT NULL * @since V0.1/public string Executesucce
SS (String cmd) {string result= ""; try {if (login ()) {session session= conn.opensession ();
ExecCommand (cmd);//execute Command result=processstdout (session.getstdout (), Defaultchart);
Conn.close ();
Session.close ();
} catch (IOException e) {e.printstacktrace (); } RETurn result; /** * Parse script execution returned result set * @author Ickes * @param in Input stream object * @param charset encoding * @sin
CE V0.1 * @return * return in plain text/private String processstdout (InputStream in, string charset) {
InputStream stdout = new Streamgobbler (in);
StringBuffer buffer = new StringBuffer ();;
try {bufferedreader br = new BufferedReader (new InputStreamReader (Stdout,charset));
String Line=null;
while ((Line=br.readline ())!= null) {buffer.append (line+ "\ n");
} catch (Unsupportedencodingexception e) {e.printstacktrace ();
catch (IOException e) {e.printstacktrace ();
return buffer.tostring ();
The public static void Setcharset (String charset) {Defaultchart = charset; Public Connection Getconn () {return COnn
public void Setconn (Connection conn) {this.conn = conn;
Public String GetIP () {return IP;
public void setIp (String IP) {this.ip = IP;
Public String GetUserName () {return userName;
} public void Setusername (String userName) {this.username = UserName;
Public String getuserpwd () {return userpwd;
} public void Setuserpwd (String userpwd) {this.userpwd = userpwd; }
}
Test code: