1. 程式人生 > 其它 >java執行shell命令工具類

java執行shell命令工具類

import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * @author :cuilei
 * @description:主要呼叫ssh2和io的包,用於遠端執行一兩條命令,沒加任何過濾限制,謹慎使用
 * @date :2020/8/17 11:18
 */
public class ExecShellUtil {
    private final static Logger logger = LoggerFactory.getLogger(ExecShellUtil.class);

    private String IP;//要遠端登入的IP地址
    private String username;//使用者名稱
    private String password;//密碼

    public ExecShellUtil(String IP, String username,String password){
        this.IP=IP;
        this.username=username;
        this.password=password;
    }

    //命令執行
    public boolean exec(String command) throws InterruptedException{
        boolean rtn = false;
        try {
            Connection conn = new Connection(IP);
            conn.connect();
            boolean isAuthenticated = conn.authenticateWithPassword(username, password);
            if (isAuthenticated == false){
                throw new IOException("Authentication failed.");
            }
            logger.info("=======================>>>"+IP+"-"+username+"<<<=======================");
            logger.info("command: "+command);
            Session sess = conn.openSession();
            sess.execCommand(command);

            InputStream stdout = new StreamGobbler(sess.getStdout());
            BufferedReader br = new BufferedReader(new InputStreamReader(stdout));

            InputStream stderr = new StreamGobbler(sess.getStderr());
            BufferedReader stderrReader = new BufferedReader(new InputStreamReader(stderr));

            String line = null;
            while ( (line = br.readLine())!=null )
            {
                logger.info(IP+" "+username+" out> "+line);
            }

            while (true)
            {
                line = stderrReader.readLine();
                if (line == null)
                    break;
                logger.info(IP+" "+username+" out> "+line);
            }

            /* Show exit status, if available (otherwise "null") */
            logger.info("ExitCode: " + sess.getExitStatus()+" "+IP+":"+command);
            sess.close();
            conn.close();
            rtn = new Integer(0).equals(sess.getExitStatus());
            return rtn;
        } catch (IOException e) {
            logger.warn("Error ......",e);
            e.printStackTrace();
            System.exit(2);
            return rtn;
        }
    }





/*    public static void main(String[] args) throws InterruptedException {

        ExecShellUtil es = new ExecShellUtil("192.168.1.16","topcom","lenovo123");
        System.out.println("==========================================單個命令測試執行==========================================");
        es.exec("ls");//執行單行命令
        System.out.println("==========================================多個命令測試執行==========================================");
        es.exec("cd /home/xcl/spider/weibo_pc_spider_local/bin/ && ls && date");//多個命令之間使用&&隔開
        //ganyMedUtil.execMoreShellCommand("");
        //ganyMedUtil.exec("ls");

    }*/
}