Java implementation ssh login host command to execute shell commands

Java implementation ssh login host command to execute shell commands


 

1, SSH command

SSH is S ecure Sh ELL  abbreviations, developed by IETF Network Group (Network Working Group); SSH is established on the basis of the application layer security protocol. SSH is a more reliable and specific for the remote login for providing security protocol session and other network services. SSH protocol can effectively prevent the use of remote management in the process of information disclosure issue. SSH was originally a program on UNIX systems, and later quickly spread to other operating platforms. SSH when used properly can make up for network vulnerabilities. SSH client for multiple platforms. Almost all UNIX platforms - including the HP-UX , Linux , AIX , the Solaris , Digital UNIX , Irix , and other platforms, can run SSH.  

 

Practice, we often use the client tools (such as: Secure CRT, Xshell, MobaXterm etc.) SSH to the host, perform some operation command.

How to use the Java language SSH connection to the host, and execute the Shell command it?

 

2, Java implementation of the SSH command 

1) code is implemented as follows:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.Calendar;

import org.apache.commons.lang3.StringUtils;

import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;


public class SshUtil {
    private static String DEFAULT_CHAR_SET = "UTF-8";
    private staticString tipStr = "=======================% s ===================== == " ;
     Private  static String splitStr =" ======================================== ============= " ; 
 
    / ** 
     * Login host 
     * @return 
     * Log returns true if successful, otherwise false 
     * / 
    public  static Connection the Login (ip String, String userName, String password) {
         Boolean isAuthenticated = to false ; 
        Connection Conn = null ;
         Long the startTime = Calendar.getInstance () getTimeInMillis ();.
         the try { 
            Conn= New new Connection (IP); 
            conn.connect (); // connecting host 

            isAuthenticated = conn.authenticateWithPassword (the userName, password); // authentication 
            IF (isAuthenticated) { 
                System.out.println (String.format (tipStr, "certification success " )); 
            } the else { 
                System.out.println (String.format (tipStr, " authentication failure " )); 
            } 
        } the catch (IOException E) { 
            System.err.println (String.format (tipStr, " Login failed " )); 
            e.printStackTrace (); 
        } 
        Long endTime =Calendar.getInstance () getTimeInMillis ();. 
        System.out.println ( "login with:" + (endTime - the startTime) /1000.0 + "S \ n-" + splitStr);
         return Conn; 
    } 
 
    / ** 
     * remote execution shell script or command 
     * @param cmd 
     * command to be executed 
     * @return 
     * value after the command execution result returned 
     * / 
    public  static String execute (Connection Conn, String cmd) { 
        String result = "" ; 
        the Session the session = null ;
         the try {
             IF (Conn! = null ) {
                the session = conn.openSession ();   // open a session 
                session.execCommand (cmd);       // Run 
                Result = processStdout (session.getStdout (), DEFAULT_CHAR_SET); 

                // if the output is obtained as the standard blank, the script execution instructions wrong 
                IF (StringUtils.isBlank (Result)) { 
                    System.err.println ( "standard output obtained [empty] \ n execution command is as follows: \ n" + cmd); 
                    Result = processStdout (session.getStderr (), DEFAULT_CHAR_SET); 
                } the else { 
                    System.out.println ( "Run successfully] [\ n execution command is as follows: \ n" + 
            } cmd);
                }
        } The catch (IOException E) { 
            System.err.println ( "[] Run failed \ n execution command is as follows: \ n" + cmd + "\ n" + e.getMessage ()); 
            e.printStackTrace (); 
        } the finally {
             IF (! Conn = null ) { 
                conn.Close (); 
            } 
            IF (the session =! null ) { 
                Session.close (); 
            } 
        } 
        return result; 
    } 

    / ** 
     * returns the analysis result of the script execution set 
     * @param in the input stream object 
     * @param charset 编码
     * @return
     *       以纯文本的格式返回
     */
    private static 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-" ); 
            } 
        } the catch (UnsupportedEncodingException E) { 
            System.err.println ( "Error analysis scenario:" + e.getMessage ()); 
            e.printStackTrace (); 
        } the catch (IOException E) { 
            the System. err.println ( "error analysis scenario:" + e.getMessage ()); 
            e.printStackTrace (); 
        } 
        return buffer.toString (); 
    } 

    public  static  void main (String [] args) { 
        String IP = " 192.168. 123.234 ";    // here the actual situation into their own need to access the host IP 
        String userName = "root" ; 
        String password = "password" ; 
        Connection conn =   SshUtil.login (ip, userName, password); 

        String cmd = "cd / Home / LS && && && pwd Miracle luna.txt CAT " ; 
        String result = SshUtil.execute (Conn, cmd); 
        System.out.println (splitStr +" \ n as the result of the execution: \ n "+ result + splitStr); 
    } 
}

 

2) The results are as follows:

======================= ======================= successful authentication 
login with : 0 .859s
 ============================================== ======= 
[Run] successful 
command execution is as follows: 
cd / Home / Miracle LS && && && pwd CAT luna.txt
 ======================== ============================= 
results performed are as follows:
 / Home / Miracle 
luna.txt 
the Hello, the I 'm SshUtil. 
Nice to you Meet. ^ _ ^ 
============================================ =========

 

3) pom.xml add the following references:

        <!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 -->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.9</version>
        </dependency>

        <!-- ssh  -->
        <dependency>
            <groupId>ch.ethz.ganymed</groupId>
            <artifactId>ganymed-ssh2</artifactId>
            <version>262</version>
        </dependency>

 

 

PS:

jar package download Maven dependency issues, please refer to the following blog post:

https://www.cnblogs.com/miracle-luna/p/11863679.html

Guess you like

Origin www.cnblogs.com/miracle-luna/p/12050367.html