Newer
Older
CasicTimeGuard / src / com / casic / swing / utils / CommandUtil.java
Pengxh on 9 Dec 2021 2 KB 界面微调
package com.casic.swing.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.concurrent.TimeUnit;

/**
 * @author a203
 */
public class CommandUtil {
    /**
     * 检查当前系统是否已安装NTP
     */
    public static boolean checkEnv() {
        System.out.println("检查当前系统是否支持NTP");
        try {
            Process exec = Runtime.getRuntime().exec("rpm -q ntp");
            try {
                //等待命令执行完成
                exec.waitFor(5, TimeUnit.SECONDS);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            String result = parseResult(exec.getInputStream());
            return !result.isEmpty();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 安装NTP
     * yum -y install ntp
     * */

    /**
     * 授时同步
     * ntpdate -u ntp.api.bz
     */
    public static String ntpDate(String host) {
        try {
            String command = "ntpdate -u " + host;
            System.out.println("授时同步 ===> " + command);
            Process exec = Runtime.getRuntime().exec(command);
            try {
                //等待命令执行完成
                exec.waitFor(5, TimeUnit.SECONDS);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return parseResult(exec.getInputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 解析命令结果
     */
    private static String parseResult(InputStream inputStream) throws IOException {
        // 读取输出流内容
        InputStreamReader streamReader = new InputStreamReader(inputStream, Charset.defaultCharset());
        BufferedReader reader = new BufferedReader(streamReader);
        StringBuilder builder = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            builder.append(line).append("\n");
        }
        return builder.toString();
    }
}