java remote call linux command or script

Java executes remote shell script via SSH2 protocol (ganymed-ssh2-build210.jar)

The Jar package of the tool is available at: http://www.ganymed.ethz.ch/ssh2/Download
ganymed-ssh2 Introduction:
Ganymed SSH-2 for Java is a package that implements the SSH-2 protocol in pure Java. In the process of using it, it is very easy, you only need to specify a valid user name password,
or authorization authentication file, you can create a connection to a remote Linux host, call the script file on the Linux host in the established session, and execute the relevant operating.
Usage: add ganymed-ssh2-build210.jar to the project's lib.

The steps are as follows:

The first step, guide package

Official website download:

http://www.ganymed.ethz.ch/ssh2/

maven coordinates:

Java代码  收藏代码
<dependency>  
  <groupId>com.ganymed.ssh2</groupId>  
  <artifactId>ganymed-ssh2-build</artifactId>  
  <version>210</version>  
 </dependency>  

The second step, apI description

  1. First construct a connector and pass in an IP address that needs to be logged in

Connection conn = new Connection(hostname);

  1. User name and password passed in to the simulated login destination server,

boolean isAuthenticated = conn.authenticateWithPassword (username,
password); it will return a boolean, true means successful login to the destination server, otherwise the login fails

  1. Open a session, a bit like a Hibernate session, execute the linux script command you need.

Session sess = conn.openSession();

sess.execCommand(“last”);

  1. Receive the results from the console on the target server and read the content in br

InputStream stdout = new StreamGobbler(sess.getStdout());

BufferedReader br = new BufferedReader(new InputStreamReader(stdout));

5. Get the flag of whether the script runs successfully: 0-success is not 0-failure

System.out.println("ExitCode: " + sess.getExitStatus());

6. Close the session and connection

sess.close();

conn.close();

Remarks:

1. After successful authentication in step 2, the current directory is located under the / home / username / directory, you can specify the absolute path where the script file is located, or navigate to the directory where the script file is located through cd, and then pass it to execute the script. Parameters, complete the script call execution.

2. After the script is executed, the text of the script execution result can be obtained. These texts need to be properly encoded and returned to the client to avoid garbled characters.

3. If you need to execute multiple linux console scripts, for example, the return result of the first script is the input parameter of the second script, you must open multiple sessions, that is, multiple calls

Session sess = conn.openSession () ;, remember to close it after use

The third step, example code, this class can be directly copied in 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;  
  
/** 
 * 远程执行linux的shell script 
 * @author Ickes 
 * @since  V0.1 
 */  
public class RemoteExecuteCommand {  
    //字符编码默认是utf-8  
    private static String  DEFAULTCHART="UTF-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() {  
          
    }  
      
    /** 
     * 远程登录linux的主机 
     * @author Ickes 
     * @since  V0.1 
     * @return 
     *      登录成功返回true,否则返回false 
     */  
    public Boolean login(){  
        boolean flg=false;  
        try {  
            conn = new Connection(ip);  
            conn.connect();//连接  
            flg=conn.authenticateWithPassword(userName, userPwd);//认证  
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
        return flg;  
    }  
    /** 
     * @author Ickes 
     * 远程执行shll脚本或者命令 
     * @param cmd 
     *      即将执行的命令 
     * @return 
     *      命令执行完后返回的结果值 
     * @since V0.1 
     */  
    public String execute(String cmd){  
        String result="";  
        try {  
            if(login()){  
                Session session= conn.openSession();//打开一个会话  
                session.execCommand(cmd);//执行命令  
                result=processStdout(session.getStdout(),DEFAULTCHART);  
                //如果为得到标准输出为空,说明脚本执行出错了  
                if(StringUtils.isBlank(result)){  
                    result=processStdout(session.getStderr(),DEFAULTCHART);  
                }  
                conn.close();  
                session.close();  
            }  
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
        return result;  
    }  
      
      
    /** 
     * @author Ickes 
     * 远程执行shll脚本或者命令 
     * @param cmd 
     *      即将执行的命令 
     * @return 
     *      命令执行成功后返回的结果值,如果命令执行失败,返回空字符串,不是null 
     * @since V0.1 
     */  
    public String executeSuccess(String cmd){  
        String result="";  
        try {  
            if(login()){  
                Session session= conn.openSession();//打开一个会话  
                session.execCommand(cmd);//执行命令  
                result=processStdout(session.getStdout(),DEFAULTCHART);  
                conn.close();  
                session.close();  
            }  
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
        return result;  
    }  
      
   /** 
    * 解析脚本执行返回的结果集 
    * @author Ickes 
    * @param in 输入流对象 
    * @param charset 编码 
    * @since V0.1 
    * @return 
    *       以纯文本的格式返回 
    */  
    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();  
    }  
      
    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:

public static void main(String[] args) {  
        RemoteExecuteCommand rec=new RemoteExecuteCommand("192.168.238.133", "root","ickes");  
        //执行命令  
        System.out.println(rec.execute("ifconfig"));  
        //执行脚本  
        rec.execute("sh /usr/local/tomcat/bin/statup.sh");  
        //这个方法与上面最大的区别就是,上面的方法,不管执行成功与否都返回,  
        //这个方法呢,如果命令或者脚本执行错误将返回空字符串  
        rec.executeSuccess("ifconfig");  
          
    }  

Packages to be imported:

<dependency>  
      <groupId>com.ganymed.ssh2</groupId>  
      <artifactId>ganymed-ssh2-build</artifactId>  
      <version>210</version>  
     </dependency>  
     <dependency>  
        <groupId>commons-io</groupId>  
        <artifactId>commons-io</artifactId>  
        <version>2.4</version>  
        <type>jar</type>  
        <scope>compile</scope>  
    </dependency>  
    <dependency>  
        <groupId>commons-lang</groupId>  
        <artifactId>commons-lang</artifactId>  
        <version>2.6</version>  
        <type>jar</type>  
        <scope>compile</scope>  
    </dependency>  
Published 156 original articles · Liked 34 · Visits 150,000+

Guess you like

Origin blog.csdn.net/bbj12345678/article/details/105531132