Java connection remote Linux Server execute Shell script view CPU, memory, hard disk information

Source: Internet
Author: User

Pom.xml Jar Package Support
<dependency>            <groupId>com.jcraft</groupId>            <artifactId>jsch</artifactId>            <version>0.1.53</version>        </dependency>

Code:

Package Com.spring.bean.annotation;import Java.io.bufferedreader;import Java.io.ioexception;import Java.io.inputstream;import Java.io.inputstreamreader;import Java.util.hashmap;import Java.util.Map;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;/** * Remote call to Linux shell command * * @author Wei. Li by 14-9-2.    */public class Linuxstateforshell {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; /** * Connect to the specified host * * @return Isconnect * @throws jschexception jschexception */private static BOOL        EAN 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;   /** * Remote connection to Linux server execution related commands * * @param commands executed script * @param user name for remote connection * @param passwd Password for remote connection * @param host IP for remote connection * @return Final command return information */public static map<string, string> rundist            Anceshell (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) {//Discard PID process information if (Buf.contains ("pid")) {                    Break                } stringbuffer.append (Buf.trim ()). append (Line_separator);            }//each command stores its own return data-for subsequent processing of the returned data 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;  }/** * Executes the shell directly locally * * @param commands executed script * @return Execution result information */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) {//Discard PID process information if (Buf.contains ("pid")) {                    Break                } stringbuffer.append (Buf.trim ()). append (Line_separator);                }} catch (IOException e) {e.printstacktrace ();            return null;        }//each command stores its own return data-for subsequent processing of the returned data map.put (command, stringbuffer.tostring ());    } return map;  /** * Processing the information returned by the shell * <p> * Specific processing process in the server return data format * Different Linux versions return information format different * * @param result  Information returned by the shell * @return final processed information */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);                    Splits the returned result by newline character for (String line:strings) {line = Line.touppercase ();//Turn uppercase processing Processing 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 (l                        Ine.startswith ("CPU (S):")) {String Cpustr = "CPU user occupancy:";                        try {cpustr + = Line.split (":") [1].split (",") [0].replace ("US", "");                            } catch (Exception e) {e.printstacktrace ();                        Cpustr + = "Error in calculation process";                        } buffer.append (CPUSTR). Append (Line_separator); Processing memory mem:66100704k Total, 65323404k used, 777300k free, 89940k buffers} else if (LINE.STARTSW                ITH ("MEM")) {        String memstr = "Memory usage:";                                    try {memstr + = Line.split (":") [1]. Replace ("Total", "totals")                                    . Replace ("used", "used"). Replace ("free", "idle")                        . Replace ("Buffers", "cache");                            } catch (Exception e) {e.printstacktrace ();                            Memstr + = "Error in calculation process";                            Buffer.append (MEMSTR). Append (Line_separator);                        Continue                    } buffer.append (MEMSTR). Append (Line_separator); }}} and Else if (Command.equals (Files_shell)) {//Processing system disk status Buffer.ap                Pend ("System disk Status:");                try {buffer.append (Disposefilessystem (Commandresult)). Append (Line_separator); } catch (EXception e) {e.printstacktrace ();                Buffer.append ("Error in calculation procedure"). Append (Line_separator);    }}} return Buffer.tostring ();    }//Processing system disk status/** * 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 processing system disk status Shell execution results * @return Processed results */private static String Disposefilessystem (String commandresult) {string[] strings = comma        Ndresult.split (Line_separator);        Final String pattern_template = "([a-za-z0-9%_/]*) \\s";        int size = 0;        int used = 0;            for (int i = 0; i < strings.length-1; i++) {if (i = = 0) continue;            int temp = 0;        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; }}}} return new StringBuilder (). Append ("size"). Append. Append ("G, used"). AP    Pend (used). Append ("G, Idle"). Append (size-used). Append ("G"). ToString ();  }/** * Processing Unit conversion * K/KB/M/T final conversion to g processing * * @param S-band unit data String * @return value in G/private            static int Disposeunit (String s) {try {s = s.touppercase ();            String LastIndex = s.substring (S.length ()-1);            String num = s.substring (0, S.length ()-1);            int parseint = Integer.parseint (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, "Dell",        "1", "192.168.1.122");    System.out.println (Disposeresultmessage (result)); }}

Java connection remote Linux Server execute Shell script view CPU, memory, hard disk information

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.