JAVA獲取遠程Linux服務器參數信息

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

import org.springframework.web.bind.annotation.RestController;

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

@RestController
public class TestController {

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);
		boolean connected = session.isConnected();
		System.out.println(connected);
		session.connect();
	} catch (JSchException e) {
		e.printStackTrace();
		System.out.println("connect error !");
		return false;
	}
	return true;
}

private static Map<String, Double> getCpuUsage() {
	Map<String, Double> map = new HashMap<String, Double>();
	double cpuUsed = 0;
	double ramUsed = 0;
	BufferedReader reader = null;
	Channel channel = null;
	try {
		channel = session.openChannel("exec");
		((ChannelExec) channel).setCommand("top -b -n 1");
		channel.setInputStream(null);
		((ChannelExec) channel).setErrStream(System.err);
		channel.connect();
		BufferedReader in = new BufferedReader(new InputStreamReader(channel.getInputStream()));
		String str = null;
		String[] strArray = null;
		while ((str = in.readLine()) != null) {
			int m = 0;
			if (str.indexOf(" R ") != -1) {// 只分析正在運行的進程,top進程本身除外 &&
				strArray = str.split(" ");
				for (String tmp : strArray) {
					if (tmp.trim().length() == 0)
						continue;
					if (++m == 9) {// 第9列爲cpu的使用百分比
						cpuUsed += Double.parseDouble(tmp);
					}
					if (m == 10) {// 第10列爲mem的使用百分比
						ramUsed += Double.parseDouble(tmp);
					}
				}
			}
		}
	} catch (IOException | JSchException e) {
		e.printStackTrace();
	} finally {
		try {
			if (reader != null) {
				reader.close();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		if (channel != null) {
			channel.disconnect();
		}
	}
	map.put("cpu", cpuUsed);
	map.put("ram", ramUsed);
	return map;
}

private static double getDiskUsage() {
	double totalhd = 0; 
    double usedhd = 0; 
	BufferedReader reader = null;
	Channel channel = null;
	try {
		channel = session.openChannel("exec");
		((ChannelExec) channel).setCommand("df -hl /");
		channel.setInputStream(null);
		((ChannelExec) channel).setErrStream(System.err);
		channel.connect();
		BufferedReader in = new BufferedReader(new InputStreamReader(channel.getInputStream()));
		String str = null; 
        String[] strArray = null; 
        while ((str = in.readLine()) != null) { 
            int m = 0; 
                strArray = str.split(" "); 
                for (String tmp : strArray) { 
                    if (tmp.trim().length() == 0) 
                        continue; 
                    ++m; 
                    if (tmp.indexOf("G") != -1) { 
                        if (m == 2) { 
                            if (!tmp.equals("") && !tmp.equals("0")) 
                                usedhd += Double.parseDouble(tmp 
                                        .substring(0, tmp.length() - 1)) * 1024; 

                        } 
                        if (m == 3) { 
                            if (!tmp.equals("none") && !tmp.equals("0")) 
                            	totalhd += Double.parseDouble(tmp.substring( 
                                        0, tmp.length() - 1)) * 1024; 

                        } 
                    } 
                    if (tmp.indexOf("M") != -1) { 
                        if (m == 2) {
                            if (!tmp.equals("") && !tmp.equals("0")) 
                            	usedhd += Double.parseDouble(tmp 
                                        .substring(0, tmp.length() - 1)); 

                        } 
                        if (m == 3) { 
                            if (!tmp.equals("none") && !tmp.equals("0")) 
                                totalhd += Double.parseDouble(tmp.substring( 
                                        0, tmp.length() - 1)); 
                        } 
                    } 
                       
                } 

          } 
	} catch (IOException | JSchException e) {
		e.printStackTrace();
	} finally {
		try {
			if (reader != null) {
				reader.close();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		if (channel != null) {
			channel.disconnect();
		}
	}
	return (totalhd / usedhd) * 100;
}

public static void main(String[] args) {
	if (!TestController.connect("username", "password", "ip")) {
		return ;
	}
	long currentTimeMillis = System.currentTimeMillis();
	System.out.println("---------------cpu used:" + TestController.getCpuUsage() + "%");
	System.out.println("---------------HD used:" + TestController.getDiskUsage() + "%");
	System.out.println(session.isConnected());
	session.disconnect();
	System.out.println(session.isConnected());
	long currentTimeMillis2 = System.currentTimeMillis();
	System.out.println(currentTimeMillis2 - currentTimeMillis);
}

}

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