GANYMED-SSH2 Introduction

Source: Internet
Author: User
Tags readline ssh
Ganymed SSH-2 for Java is a package that implements the SSH-2 protocol in pure Java. In the process of using it is very easy, only to specify a legitimate username password, or authorization to authenticate files, you can create a connection to a remote Linux host, in the established session of the Linux host to invoke the script file, to perform related operations. How to: Add Ganymed-ssh2-build210.jar to the project's lib. Simple example:

Suppose I devolve a folder Test,test folder corresponding to the test Java class's package name in the/home/lldu directory of 192.168.0.114 Linux system, and we use Javac on that 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 {
            Co Nnection 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, passing in a need to login IP address

Connection conn = new Connection (ipaddr);
Conn.connect (); Connection


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 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 ();

What needs to be stated is:
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.

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


Extracts part of the source code 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 lo Caldir) 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 other computers public static void Scpput (string host, string username, string password, string localfile, String R Emotedir) 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 the SSH command. public static int Runssh (string host, string username, string password, string cmd) throws IOException {if (logger.i 
Sdebugenabled ()) {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 Ioexcept Ion {if (logger.isdebugenabled ()) {logger.debug ("Connecting to" + Host + "with user" + Username + "and PW 
D "+ 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; //execute the local cmd command. (DOS command) public static int runlocal (String cmd) throws IOException {if (logger.isdebugenabled ()) {Logger.debug ("Runn 
ing 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 (); } 
}

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.