Java實現通過ssh遠程連接主機並執行命令

需要用到的jar包:

主體代碼: 

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;
public class SshLinux {
    private static final Logger log = LoggerFactory.getLogger(SshLinux.class);
    private static String  DEFAULTCHART="UTF-8";

    /**
     * 登錄主機
     * @return
     *      登錄成功返回true,否則返回false
     */
    public static Connection login(String ip,
                                   String userName,
                                   String userPwd){

        boolean flg=false;
        Connection conn = null;
        try {
            conn = new Connection(ip);
            conn.connect();//連接
            flg=conn.authenticateWithPassword(userName, userPwd);//認證
            if(flg){
                log.info("=========登錄成功========="+conn);
                return conn;
            }
        } catch (IOException e) {
            log.error("=========登錄失敗========="+e.getMessage());
            e.printStackTrace();
        }
        return conn;
    }

    /**
     * 遠程執行shll腳本或者命令
     * @param cmd
     *      即將執行的命令
     * @return
     *      命令執行完後返回的結果值
     */
    public static String execute(Connection conn,String cmd){
        String result="";
        try {
            if(conn !=null){
                Session session= conn.openSession();//打開一個會話
                session.execCommand(cmd);//執行命令
                result=processStdout(session.getStdout(),DEFAULTCHART);
                //如果爲得到標準輸出爲空,說明腳本執行出錯了
                if(StringUtils.isBlank(result)){
                    log.info("得到標準輸出爲空,鏈接conn:"+conn+",執行的命令:"+cmd);
                    result=processStdout(session.getStderr(),DEFAULTCHART);
                }else{
                    log.info("執行命令成功,鏈接conn:"+conn+",執行的命令:"+cmd);
                }
                conn.close();
                session.close();
            }
        } catch (IOException e) {
            log.info("執行命令失敗,鏈接conn:"+conn+",執行的命令:"+cmd+"  "+e.getMessage());
            e.printStackTrace();
        }
        return result;
    }
    /**
     * 解析腳本執行返回的結果集
     * @param in 輸入流對象
     * @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");
            }
        } catch (UnsupportedEncodingException e) {
            log.error("解析腳本出錯:"+e.getMessage());
            e.printStackTrace();
        } catch (IOException e) {
            log.error("解析腳本出錯:"+e.getMessage());
            e.printStackTrace();
        }
        return buffer.toString();
    }
}

注意:ganymed這個jar包,每次只能執行一條命令,如果一條命令執行了沒有關閉,再去執行第二條則會throw new IOException("A remote execution has already started.");

若希望同時執行多條命令,可以在傳入的cmd字符串中用&&連接多條命令。

如:

那麼多條命令執行的所有結果將會一同作爲返回的字符串。 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章