Java 連接遠程Linux 服務器執行 shell 腳本查看 CPU、內存、硬盤信息

pom.xml jar 包支持

   <dependency>
            <groupId>com.jcraft</groupId>
            <artifactId>jsch</artifactId>
            <version>0.1.53</version>
        </dependency>

 JAVA代碼

package test2;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.NumberFormat;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;

/**
 * 遠程調用Linux shell 命令
 *
 * @author wei.Li by 14-9-2.
 */
public class CPUTest {
	public static final String DIR_NAME="/boot";
    public static final String CPU_MEM_SHELL = "top -b -n 1";
    public static final String FILES_SHELL = "df -hl";
    public static final String[] COMMANDS = {CPU_MEM_SHELL, FILES_SHELL};
    public static final String LINE_SEPARATOR = System.getProperty("line.separator");
    private static Session session;

    /**
     * 連接到指定的HOST
     *
     * @return isConnect
     * @throws JSchException JSchException
     */
    private static boolean connect(String user, String passwd, String host) {
        JSch jsch = new JSch();
        try {
            session = jsch.getSession(user, host, 22);
            session.setPassword(passwd);

            java.util.Properties config = new java.util.Properties();
            config.put("StrictHostKeyChecking", "no");
            session.setConfig(config);

            session.connect();
        } catch (JSchException e) {
            e.printStackTrace();
            System.out.println("connect error !");
            return false;
        }
        return true;
    }

    /**
     * 遠程連接Linux 服務器 執行相關的命令
     *
     * @param commands 執行的腳本
     * @param user     遠程連接的用戶名
     * @param passwd   遠程連接的密碼
     * @param host     遠程連接的主機IP
     * @return 最終命令返回信息
     */
    public static Map<String, String> runDistanceShell(String[] commands, String user, String passwd, String host) {
        if (!connect(user, passwd, host)) {
            return null;
        }
        Map<String, String> map = new HashMap<>();
        StringBuilder stringBuffer;

        BufferedReader reader = null;
        Channel channel = null;
        try {
            for (String command : commands) {
                stringBuffer = new StringBuilder();
                channel = session.openChannel("exec");
                ((ChannelExec) channel).setCommand(command);

                channel.setInputStream(null);
                ((ChannelExec) channel).setErrStream(System.err);

                channel.connect();
                InputStream in = channel.getInputStream();
                reader = new BufferedReader(new InputStreamReader(in));
                String buf;
                while ((buf = reader.readLine()) != null) {

                    //捨棄PID 進程信息
                    if (buf.contains("PID")) {
                        break;
                    }
                    stringBuffer.append(buf.trim()).append(LINE_SEPARATOR);
                }
                //每個命令存儲自己返回數據-用於後續對返回數據進行處理
                map.put(command, stringBuffer.toString());
            }
        } catch (IOException | JSchException e) {
            e.printStackTrace();
        } finally {
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (channel != null) {
                channel.disconnect();
            }
            session.disconnect();
        }
        return map;
    }


    /**
     * 直接在本地執行 shell
     *
     * @param commands 執行的腳本
     * @return 執行結果信息
     */
    public static Map<String, String> runLocalShell(String[] commands) {
        Runtime runtime = Runtime.getRuntime();

        Map<String, String> map = new HashMap<>();
        StringBuilder stringBuffer;

        BufferedReader reader;
        Process process;
        for (String command : commands) {
            stringBuffer = new StringBuilder();
            try {
                process = runtime.exec(command);
                InputStream inputStream = process.getInputStream();
                reader = new BufferedReader(new InputStreamReader(inputStream));
                String buf;
                while ((buf = reader.readLine()) != null) {
                    //捨棄PID 進程信息
                    if (buf.contains("PID")) {
                        break;
                    }
                    stringBuffer.append(buf.trim()).append(LINE_SEPARATOR);
                }

            } catch (IOException e) {
                e.printStackTrace();
                return null;
            }
            //每個命令存儲自己返回數據-用於後續對返回數據進行處理
            map.put(command, stringBuffer.toString());
        }
        return map;
    }


    /**
     * 處理 shell 返回的信息
     * <p>
     * 具體處理過程以服務器返回數據格式爲準
     * 不同的Linux 版本返回信息格式不同
     *
     * @param result shell 返回的信息
     * @return 最終處理後的信息
     */
    private static String disposeResultMessage(Map<String, String> result) {

        StringBuilder buffer = new StringBuilder();

        for (String command : COMMANDS) {
            String commandResult = result.get(command);
            if (null == commandResult) continue;

            if (command.equals(CPU_MEM_SHELL)) {
                String[] strings = commandResult.split(LINE_SEPARATOR);
                //將返回結果按換行符分割
                for (String line : strings) {
                    line = line.toUpperCase();//轉大寫處理

                    //處理CPU Cpu(s): 10.8%us,  0.9%sy,  0.0%ni, 87.6%id,  0.7%wa,  0.0%hi,  0.0%si,  0.0%st
                    if (line.startsWith("CPU(S):")) {
                        String cpuStr = "CPU 用戶使用佔有率:";
                        try {
                            cpuStr += line.split(":")[1].split(",")[0].replace("US", "");
                        } catch (Exception e) {
                            e.printStackTrace();
                            cpuStr += "計算過程出錯";
                        }
                        buffer.append(cpuStr).append(LINE_SEPARATOR);

                        //處理內存 Mem:  66100704k total, 65323404k used,   777300k free,    89940k buffers
                    } else if (line.startsWith("MEM")) {
                        String memStr = "內存使用情況:";
                        try {
                            memStr += line.split(":")[1]
                                    .replace("TOTAL", "總計")
                                    .replace("USED", "已使用")
                                    .replace("FREE", "空閒")
                                    .replace("BUFFERS", "緩存");

                        } catch (Exception e) {
                            e.printStackTrace();
                            memStr += "計算過程出錯";
                            buffer.append(memStr).append(LINE_SEPARATOR);
                            continue;
                        }
                        buffer.append(memStr).append(LINE_SEPARATOR);

                    }
                }
            } else if (command.equals(FILES_SHELL)) {
                //處理系統磁盤狀態
                buffer.append("系統磁盤狀態:");
                try {
                    buffer.append(disposeFilesSystem(commandResult)).append(LINE_SEPARATOR);
                } catch (Exception e) {
                    e.printStackTrace();
                    buffer.append("計算過程出錯").append(LINE_SEPARATOR);
                }
            }
        }

        return buffer.toString();
    }

    //處理系統磁盤狀態

    /**
     * Filesystem            Size  Used Avail Use% Mounted on
     * /dev/sda3             442G  327G   93G  78% /
     * tmpfs                  32G     0   32G   0% /dev/shm
     * /dev/sda1             788M   60M  689M   8% /boot
     * /dev/md0              1.9T  483G  1.4T  26% /ezsonar
     *
     * @param commandResult 處理系統磁盤狀態shell執行結果
     * @return 處理後的結果
     */
    private static String disposeFilesSystem(String commandResult) {
        String[] strings = commandResult.split(LINE_SEPARATOR);

        // final String PATTERN_TEMPLATE = "([a-zA-Z0-9%_/]*)\\s";
        Double size = 0.0;
        Double used = 0.0;
        for (int i = 0; i < strings.length - 1; i++) {
            if (i == 0) continue;
            if(StringUtils.isNotBlank(DIR_NAME)){
            	//不指定目錄則查看所有內存使用
            	if(!strings[i].endsWith(DIR_NAME)) continue;
            }
            int temp = 0;
            for (String s : strings[i].split(" +")) {
//        	for (String s : strings[i].split("\\b")) {
                if (temp == 0) {
                    temp++;
                    continue;
                }
                if (!s.trim().isEmpty()) {
                    if (temp == 1) {
                        size += disposeUnit(s);
                        temp++;
                    } else {
                        used += disposeUnit(s);
                        temp = 0;
                    }
                }
            }
        }
        String numPercent = getNumPercent(used,size);
        System.out.println("內存使用率:"+numPercent);
        return new StringBuilder().append("大小 ").append(size).append("G , 已使用").append(used).append("G ,空閒")
                .append(size - used).append("G").toString();
    }
    public static String getNumPercent(Double num1,Double num2){
		if(num2==0){
			return "0%";
		}
		// 創建一個數值格式化對象
		NumberFormat numberFormat = NumberFormat.getInstance();
		// 設置精確到小數點後2位
		numberFormat.setMaximumFractionDigits(2);
		return numberFormat.format(num1 /  num2 * 100)+ "%";
	}

    /**
     * 處理單位轉換
     * K/KB/M/T 最終轉換爲G 處理
     *
     * @param s 帶單位的數據字符串
     * @return 以G 爲單位處理後的數值
     */
    private static double disposeUnit(String s) {

        try {
            s = s.toUpperCase();
            String lastIndex = s.substring(s.length() - 1);
            String num = s.substring(0, s.length() - 1);
            double parseInt = Double.parseDouble(num);
            if (lastIndex.equals("G")) {
                return parseInt;
            } else if (lastIndex.equals("T")) {
                return parseInt * 1024;
            } else if (lastIndex.equals("M")) {
                return parseInt / 1024;
            } else if (lastIndex.equals("K") || lastIndex.equals("KB")) {
                return parseInt / (1024 * 1024);
            }
        } catch (NumberFormatException e) {
            e.printStackTrace();
            return 0;
        }
        return 0;
    }

    public static void main(String[] args) {
        Map<String, String> result = runDistanceShell(COMMANDS, "root", "Netinfo@dev",
        		"172.16.4.32");
        System.out.println(disposeResultMessage(result));
    }

}

 

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