Java executes remote shell scripts via the SSH2 Protocol (GANYMED-SSH2-BUILD210.JAR)

Source: Internet
Author: User
Tags linux script command



The tool jar package is available in: http://download.csdn.net/detail/shenjianox/7769783 and documentation

GANYMED-SSH2 Introduction:

Ganymed SSH-2 for Java is a package that implements the SSH-2 protocol with pure Java. It's very easy to use it, just specify a valid username password,
Or authorize the authentication file, you can create a connection to the remote Linux host, invoke the script file on the Linux host in the established session, and perform the related operation.


How to use:
Add Ganymed-ssh2-build210.jar to the project's lib.

Simple example:

Suppose I put a folder in the/home/lldu directory of the 192.168.0.114 Linux system test,test folder corresponding to the package name test of the Java class, we use Javac on the machine./test/ Main.java compiles, and then completes the remote call by calling the following code:

Import ch.ethz.ssh2.Connection;
Import Ch.ethz.ssh2.ConnectionInfo;
Import ch.ethz.ssh2.Session;
/**
*
* @author Lldu
*/
public class Main {
public static void Main (string[] args) {
try {
Connection con = new Connection ("192.168.0.114");
ConnectionInfo info = Con.connect ();
Boolean result = Con.authenticatewithpassword ("Lldu", "123456");
Session session = Con.opensession ();
Session.execcommand ("Java test. Main ");
} catch (Exception ex) {
System.out.println (Ex.getlocalizedmessage ());
}
}
}

Summary use steps:

1. First construct a connector and pass in an IP address that needs to be logged in
Connection conn = new Connection (IPADDR);
Conn.connect (); Connection


2. Impersonate the login destination server incoming user name and password,
Boolean isauthenticated = Conn.authenticatewithpassword (username, password); it returns a Boolean value that is true for successful login to the destination server, otherwise the login fails

3. Open a session, a bit like hibernate session, execute the Linux script command you need.
Session sess = Conn.opensession ();
Sess.execcommand ("last");

4. Receive the results from the console 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. Flag to get the script to run successfully: 0-Success not 0-failure
System.out.println ("ExitCode:" + sess.getexitstatus ());

6. Close session and connection
Sess.close ();
Conn.close ();

It should be stated that:
1. After the success of the 2nd step authentication, the current directory is located under the/home/username/directory, you can specify the absolute path of the script file, or navigate to the directory where the script file is located by the CD, and then pass the parameters required to execute the script, complete the script call execution.

2. After executing the script, you can get the result text of the script execution, which needs to be correctly encoded and returned to the client to avoid garbled characters.

3. If you need to execute multiple Linux console scripts, such as the first script's return result is the second script entry, you must open multiple sessions, that is, multiple calls
Session sess = conn.opensession (), use finished remember to close it

=================================================================================================

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 files from other networked computers
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 another 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 ();
}
Executes the SSH command.
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.getstdout ());
BufferedReader br = new BufferedReader (new InputStreamReader (stdout));
while (true) {
String line = Br.readline ();
if (line = = null)
Break
if (logger.isdebugenabled ()) {
Logger.debug (line);
}
}
Sess.close ();
Conn.close ();
Return Sess.getexitstatus (). Intvalue ();
}
Get Connected
private static Connection Getopenedconnection (string host, String username,
String password) throws IOException {
if (logger.isdebugenabled ()) {
Logger.debug ("Connecting to" + Host + "with user" + username
+ "and pwd" + password);
}
Connection conn = new Connection (host);
Conn.connect (); Make sure the connection is opened
Boolean isauthenticated = Conn.authenticatewithpassword (username,
password);
if (isauthenticated = = False)
throw new IOException ("Authentication failed.");
Return conn;
}
Executes the local cmd command. (DOS command)
public static int runlocal (String cmd) throws IOException {
if (logger.isdebugenabled ()) {
Logger.debug ("Running local cmd [" + cmd + "]");
}
Runtime RT = Runtime.getruntime ();
Process p = rt.exec (cmd);
InputStream stdout = new Streamgobbler (P.getinputstream ());
BufferedReader br = new BufferedReader (new InputStreamReader (stdout));
while (true) {
String line = Br.readline ();
if (line = = null)
Break
if (logger.isdebugenabled ()) {
Logger.debug (line);
}
}
return P.exitvalue ();
}
}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.