java ssh遠程服務器並執行多條shell命令


 

java ssh遠程服務器並執行多條命令

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 static String tipStr = "=======================%s=======================";
    private static String splitStr = "=====================================================";

    /**
     * 登錄主機
     * @return
     *  登錄成功返回true,否則返回false
     */
    public static Connection login(String ip, String userName, String password){
        boolean isAuthenticated = false;
        Connection conn = null;
        long startTime = Calendar.getInstance().getTimeInMillis();
        try {
            conn = new Connection(ip);
            conn.connect(); // 連接主機

            isAuthenticated = conn.authenticateWithPassword(userName, password); // 認證
            if(isAuthenticated){
                System.out.println(String.format(tipStr, "認證成功"));
            } else {
                System.out.println(String.format(tipStr, "認證失敗"));
            }
        } catch (IOException e) {
            System.err.println(String.format(tipStr, "登錄失敗"));
            e.printStackTrace();
        }
        long endTime = Calendar.getInstance().getTimeInMillis();
        System.out.println("登錄用時: " + (endTime - startTime)/1000.0 + "s\n" + splitStr);
        return conn;
    }

    /**
     * 遠程執行shell腳本或者命令
     * @param cmd
     *  即將執行的命令
     * @return
     *  命令執行完后返回的結果值
     */
    public static String execute(Connection conn, String cmd){
        String result = "";
        Session session = null;
        try {
            if(conn != null){
                session = conn.openSession(); // 打開一個會話
                session.execCommand(cmd);  // 執行命令
                result = processStdout(session.getStdout(), DEFAULT_CHAR_SET);

                //如果為得到標准輸出為空,說明腳本執行出錯了
                if(StringUtils.isBlank(result)){
                    System.err.println("【得到標准輸出為空】\n執行的命令如下:\n" + cmd);
                    result = processStdout(session.getStderr(), DEFAULT_CHAR_SET);
                }else{
                    System.out.println("【執行命令成功】\n執行的命令如下:\n" + cmd);
                }
            }
        } catch (IOException e) {
            System.err.println("【執行命令失敗】\n執行的命令如下:\n" + cmd + "\n" + e.getMessage());
            e.printStackTrace();
        } finally {
            if (conn != null) {
                conn.close();
            }
            if (session != null) {
                session.close();
            }
        }
        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) {
            System.err.println("解析腳本出錯:" + e.getMessage());
            e.printStackTrace();
        } catch (IOException e) {
            System.err.println("解析腳本出錯:" + e.getMessage());
            e.printStackTrace();
        }
        return buffer.toString();
    }

    public static void main(String[] args){
        String ip = "192.168.56.88"; // 此處根據實際情況,換成自己需要訪問的主機IP
        String userName = "root";
        String password = "111111";
        Connection conn = SshUtil.login(ip, userName, password);

        //多條命令可以用&&分割
        //String cmd = "cd /home/&&pwd&&ls";
        String result = SshUtil.execute(conn, cmd);
        System.out.println(splitStr + "\n執行的結果如下: \n" + result + splitStr);
    }
}

 

 需要的maven依賴

        <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>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM