JAVAはLinuxシェルコマンドをリモートで呼び出します-JAVA側を完成させて、Linxサーバーのディスク、メモリ、その他の情報を収集し、フロントエンドに返します

パッケージcom.learn.service; 
importcom.jcraft.jsch。*; 
import java.io.BufferedReader; 
import java.io.IOException; 
import java.io.InputStream; 
import java.io.InputStreamReader; 
import java.util.HashMap ; 
import java.util.Map; 

/ ** 
 * Linuxシェルコマンドをリモートで呼び出す
 * @ author yuyihao 2019.10.12 
 * / 
public class LinuxStateForShell { 
    public static final String CPU_MEM_SHELL = "top -b -n 1"; // liunxコマンドuserシステム情報を取得
    publicstatic final String FILES_SHELL = "df -hl"; //ディスク使用量を表示publicstatic 
    final String [] COMMANDS = {CPU_MEM_SHELL、FILES_SHELL}; //コマンド配列
    / **
     * Javaには、「 \ n "は新しい行の文字であり、JDKに付属している一部の演算子System.getProperty(" line.separator ");
     *これも改行文字であり、その機能は「\ n」と同じです。この方法では、Windows環境とLinux環境で改行を区別できます。
     *開発中、同じ環境ではなく、System.getProperty( "line.separator");を使用して改行を制御できます
     * / 
    public static final String LINE_SEPARATOR = System.getProperty( "line.separator"); 
    private static Session session; 

    / 
     ***
     指定されたホストに接続します* @ 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();
     * @ paramコマンドはスクリプトを実行します
     *リモート接続用の@paramユーザーユーザー名
     *リモート接続
     用の
     @parampasswdパスワード*リモート接続用の@paramホストホストIP * @returnfinalコマンドの戻り情報
            System.out.println( "接続エラー!"); 
            falseを返します。
        } 
        trueを返します。
    } 

    / 
     ***远程006接Linux服务器执行相関連的命令
     * / 
    public static Map <String、String> runDistanceShell(String []コマンド、String user、String passwd、String host)throws IOException { 
        if(!connect(user、passwd 、host)){ 
            nullを返す; 
        } 
        Map <String、String> map = new HashMap <>(); 
        StringBuilder stringBuffer; 
        BufferedReaderリーダー= null; 
        チャネルchannel = null; 
        { 
            for(String command:commands){を試してください 
                stringBuffer = new StringBuilder();を
                チャネル= 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(); 
        } final { 
            try { 
                if(reader!= null){ 
                    reader.close(); 
                } 
            } catch (IOException e){ 
                e.printStackTrace(); 
            } 
            if(channel!= null){ 
                channel.disconnect(); 
            } 
            session.disconnect(); 
        } 
        return map; 
    } 

    / ***
     シェルから返された情報を処理する
     *特定の処理このプロセスは、サーバーから返されるデータ形式の影響を受けます
     *異なるLinuxバージョンは異なる形式で情報を
     返します
     * @ paramresultシェルは情報を返します* @ 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 [] string = commandResult.split(LINE_SEPARATOR); 
                //返されたものを分割する
                    newlineによる結果
                (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 user share: "; 
                        try { 
                            cpuStr + = line.split(": ")[1] .split("、 ")[0] .replace(" US "、" "); 
                        } catch(Exception e){ 
                            e.printStackTrace(); 
                            cpuStr + ="計算中のエラー "; 
                        } 
                        buffer.append(cpuStr).append(LINE_SEPARATOR); 
                    //メモリメモリの処理:合計66100704k、65323404k使用、 777300k無料、89940kバッファ
                    } else if(line.startsWith( "MEM")){ 
                        String memStr = "メモリ使用量:"; 
                        try { 
                            memStr + = line.split( ":")[1] 
                                    .replace( "TOTAL"、 "Total")
                                    .replace( "USED"、 "Used")。
                                    replace( "FREE"、 "Free")。
                                    replace( "BUFFERS"、 "Cache"); 
                        } catch(Exception e){ 
                            e.printStackTrace(); 
                            memStr + = "計算中のエラー";
                            buffer.append(memStr).append(LINE_SEPARATOR);
                            続行; 
                        } 
                        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( "calculation error" )。append (LINE_SEPARATOR); 
                } 
            } 
        } 
        return buffer.toString( );
    } 
    //システムディスクステータスの処理

    / ** 
     * @paramcommandResultシステムディスクステータスシェルの実行結果の
     処理* @ return処理結果
     * / 
    / ***
     最終処理結果
     * CPUユーザー使用率:0.2%
     *メモリ使用状況:合計
     1020344K、使用済み160248K、空き860096K、キャッシュ14176K *システムディスクステータス:サイズ7.66G、使用済み2.93G、空き4.73G 
     * / 
    private static String disposeFilesSystem(String commandResult){ 
        String [] string = commandResult.split(LINE_SEPARATOR); 
        //最終的な文字列PATTERN_TEMPLATE = "([a-zA-Z0-9%_ /] *)\\ s"; 
        Double size = 0d; 
        Double used = 0d; 
        for(int i = 1; i <strings.length; i ++){//最初の行のタイトルは必要ありません

            String [] row = strings [i] .split( "\\ s +"); 

            size + = disposeUnit(row [1]); // 2番目に

            使用れる列のサイズ+ = disposeUnit(row [2]); //最初の3つ使用される列
        } 

        return new StringBuilder()。append( "size")。append(Math.round(size * 100)/ 100d).append( "G、used")。append(Math.round(used * 100)/ 100d).append( "G、idle")。
                append(Math.round((size-used)* 100)/ 100d).append( "G")。toString(); 
    } 

    / ***
     処理単位の変換
     * K / KB / M / Tは最終的にGに変換されます。処理
     * 
     @ paramsデータ文字列とユニット* @ return値はGユニットで処理されます
     * / 
    private static Double disposeUnit(String s){ 
        try { 
            s = s.toUpperCase() ;
            文字列lastIndex = s.substring(s.length()-1); 
            文字列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 0d; 
    } 

    public static void main(String [] args)throws IOException { 
        Map <String、String> result = runDistanceShell(COMMANDS、 "root"、 "root123"、 "192.168.56.101"); 
        System.out.println (disposeResultMessage(result)); 
    } 

}
重要なことを3回言ってください!Linuxの異なるバージョンによって実行されたコマンドによって返されるデータは異なります。特定の問題を詳細に分析する必要があります。

この例で使用されているLinxのバージョン:

top -b -n1実行後のデータ

実行後のdf-hlデータ

 

 

おすすめ

転載: blog.csdn.net/a1_HelloWord/article/details/102528261