eclipse
Linus服务器
编写代码:import java.io.IOException;import java.io.InputStream;import java.nio.charset.Charset;import ch.ethz.ssh2.Connection;import ch.ethz.ssh2.Session;public class Test { private Connection conn; //连接属性 private String ipAddr; //ip地址 private String charset = Charset.defaultCharset().toString(); //编码格式 private String userName; //连接用户名 private String password; //连接密码 public Test(String ipAddr, String userName, String password, String charset) { this.ipAddr = ipAddr; this.userName = userName; this.password = password; if (charset != null) { this.charset = charset; } } public boolean login() throws IOException { conn = new Connection(ipAddr); conn.connect(); // 连接 return conn.authenticateWithPassword(userName, password); // 认证 } public String exec(String cmds) { InputStream in = null; String result = ''; try { if (this.login()) { Session session = conn.openSession(); // 打开一个会话 session.execCommand(cmds); in = session.getStdout(); result = this.processStdout(in, this.charset); session.close(); conn.close(); } } catch (IOException e1) { e1.printStackTrace(); } return result; } public String processStdout(InputStream in, String charset) { byte[] buf = new byte[1024]; StringBuffer sb = new StringBuffer(); try { while (in.read(buf) != -1) { sb.append(new String(buf, charset)); } } catch (IOException e) { e.printStackTrace(); } return sb.toString(); } /** * @param args */ public static void main(String[] args) { Test test = new Test('192.168.1.128', 'root', '123.com', 'utf-8'); ThreadGetCpuUsage threadGetCpuUsage = new ThreadGetCpuUsage(test); new Thread(threadGetCpuUsage).start(); System.out.println(test.ipAddr+'CPU使用率:'); } } class ThreadGetCpuUsage implements Runnable{ Test tool; ThreadGetCpuUsage(Test tool){ this.tool = tool; } @Override public void run() { // TODO Auto-generated method stub while(true){ try { Thread.sleep(1); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } String result = tool.exec('./getCpuUsage.sh'); result = result.substring(0,result.indexOf('%')); //System.out.println('取得数值:'); float convertResult=new Float(result)/100; System.out.println('CPU使用率为:'+convertResult); } } }连接属性配置:
Run As
ganymed-ssh2-262.jar一定要导入正确
float convertResult=new Float(result)/100; 这一步关键点,百分比转换成单精度类型