pom.xml jar 包支持

    <dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>0.1.53</version>
</dependency>

代码:

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; /**
* 远程调用Linux shell 命令
*
* @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; /**
* 连接到指定的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); session.connect();
} catch (JSchException e) {
e.printStackTrace();
System.out.println("connect error !");
return false;
}
return true;
} /**
* 远程连接Linux 服务器 执行相关的命令
*
* @param commands 执行的脚本
* @param user 远程连接的用户名
* @param passwd 远程连接的密码
* @param host 远程连接的主机IP
* @return 最终命令返回信息
*/
public static Map<String, String> runDistanceShell(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) { //舍弃PID 进程信息
if (buf.contains("PID")) {
break;
}
stringBuffer.append(buf.trim()).append(LINE_SEPARATOR);
}
//每个命令存储自己返回数据-用于后续对返回数据进行处理
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;
} /**
* 直接在本地执行 shell
*
* @param commands 执行的脚本
* @return 执行结果信息
*/
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) {
//舍弃PID 进程信息
if (buf.contains("PID")) {
break;
}
stringBuffer.append(buf.trim()).append(LINE_SEPARATOR);
} } catch (IOException e) {
e.printStackTrace();
return null;
}
//每个命令存储自己返回数据-用于后续对返回数据进行处理
map.put(command, stringBuffer.toString());
}
return map;
} /**
* 处理 shell 返回的信息
* <p>
* 具体处理过程以服务器返回数据格式为准
* 不同的Linux 版本返回信息格式不同
*
* @param result shell 返回的信息
* @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[] strings = commandResult.split(LINE_SEPARATOR);
//将返回结果按换行符分割
for (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 用户使用占有率:";
try {
cpuStr += line.split(":")[1].split(",")[0].replace("US", "");
} catch (Exception e) {
e.printStackTrace();
cpuStr += "计算过程出错";
}
buffer.append(cpuStr).append(LINE_SEPARATOR); //处理内存 Mem: 66100704k total, 65323404k used, 777300k free, 89940k buffers
} else if (line.startsWith("MEM")) {
String memStr = "内存使用情况:";
try {
memStr += line.split(":")[1]
.replace("TOTAL", "总计")
.replace("USED", "已使用")
.replace("FREE", "空闲")
.replace("BUFFERS", "缓存"); } catch (Exception e) {
e.printStackTrace();
memStr += "计算过程出错";
buffer.append(memStr).append(LINE_SEPARATOR);
continue;
}
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("计算过程出错").append(LINE_SEPARATOR);
}
}
} return buffer.toString();
} //处理系统磁盘状态 /**
* 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 处理系统磁盘状态shell执行结果
* @return 处理后的结果
*/
private static String disposeFilesSystem(String commandResult) {
String[] strings = commandResult.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("大小 ").append(size).append("G , 已使用").append(used).append("G ,空闲")
.append(size - used).append("G").toString();
} /**
* 处理单位转换
* K/KB/M/T 最终转换为G 处理
*
* @param s 带单位的数据字符串
* @return 以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 连接远程Linux 服务器执行 shell 脚本查看 CPU、内存、硬盘信息的更多相关文章

  1. Windows远程linux服务器执行shell命令

    一.前言 借用百度百科关于putty的描述:PuTTY是一个Telnet.SSH.rlogin.纯TCP以及串行接口连接软件.较早的版本仅支持Windows平台,在最近的版本中开始支持各类Unix平台 ...

  2. java 连接远程Linux 服务器

    创建闭锁,确保能连接到zk服务器. // 创建闭锁final CountDownLatch countDownLatch = new CountDownLatch(1); String connect ...

  3. 秘钥登录服务器执行shell脚本

    做自动化的时候,有时候避免不了要和服务器有互动,刚巧碰上一个项目,需要执行命令才能完成本次测试. 昨天遇到的是秘钥形式的,只有秘钥和用户名,百度找了许久也没有思路,(能账号密码登录服务器的还简单些), ...

  4. Linux终端执行shell脚本,提示权限不够的解决办法

    原文:http://blog.csdn.net/this_capslock/article/details/17415409 今天在Linux尝试搭建dynamips的工作环境,在执行shell脚本时 ...

  5. Linux中执行shell脚本的4种方法总结

    bash shell 脚本的方法有多种,现在作个小结.假设我们编写好的shell脚本的文件名为hello.sh,文件位置在/data/shell目录中并已有执行权限. 方法一:切换到shell脚本所在 ...

  6. Linux中执行shell脚本的4种方法

    bash shell 脚本的方法有多种,现在作个小结.假设我们编写好的shell脚本的文件名为hello.sh,文件位置在/data/shell目录中并已有执行权限. 方法一:切换到shell脚本所在 ...

  7. 每天一个linux命令(62):sh命令 /Linux中执行shell脚本的4种方法总结

    bash shell 脚本的方法有多种,现在作个小结.假设我们编写好的shell脚本的文件名为hello.sh,文件位置在/data/shell目录中并已有执行权限. 方法一:切换到shell脚本所在 ...

  8. Linux中执行shell脚本命令的4种方法总结

    bash shell 脚本的方法有多种,现在作个小结.假设我们编写好的shell脚本的文件名为hello.sh,文件位置在/data/shell目录中并已有执行权限. 方法一:切换到shell脚本所在 ...

  9. linux 执行远程linux上的shell脚本或者命令以及scp 上传文件到ftp--免密码登陆

    场景:在linux A 上执行Linux B上的shell脚本和命令 步骤1.设置ssh免登陆 1.SSH无密码登录 # 本地服务器执行(A机器):生成密钥对 ssh-keygen -t dsa -P ...

随机推荐

  1. idea打jar包没有MANIFEST文件坑

    看到横线处没有,将此处的main\java 删除掉 meta-inf文件夹必须在src文件夹下,才能打包成功, idea自动加了 main/java 会导致打包时,找不到该manifest文件,不会将 ...

  2. 使用AutoMapper实现Dto和Model的自由转换(中)

    在上一篇文章中我们构造出了完整的应用场景,包括我们的Model.Dto以及它们之间的转换规则.下面就可以卷起袖子,开始我们的AutoMapper之旅了. [二]以Convention方式实现零配置的对 ...

  3. Java进阶之路

    Java进阶之路——从初级程序员到架构师,从小工到专家. 怎样学习才能从一名Java初级程序员成长为一名合格的架构师,或者说一名合格的架构师应该有怎样的技术知识体系,这是不仅一个刚刚踏入职场的初级程序 ...

  4. 【题解】 luogu 3857 [TJOI2008]彩灯 (线性基)

    luogu3857,懒得复制 Solution: 裸的线性基,往里面添加数,记录添加个数\(sum\),快速幂输出\(2^{sum}\)即可 Code: //It is coded by Ning_M ...

  5. 【转】如何应用Query语句进行规则的语法设置?

    在Altium Designer中, 设计规则通常用来定义用户的设计需求. 这些规则涵盖了设计的方方面面, 从布线宽度, 对象的安全间距,内电层的连接风格, 过孔风格等等. 设计规则不仅能在PCB设计 ...

  6. stm32 修改工作频率

    @2018-5-11 10:04:22 修改外部晶振大小 stm32f4xx系列是在文件<stm32f4xx.h>中的宏定义 #define HSE_VALUE (uint32_t)800 ...

  7. Codeforces 468C/469E 易错点

    #include <stdio.h> #include <stdlib.h> typedef long long ll; int main() { ll x=1e17; ll ...

  8. 构造代码块----java基础总结

    前言:之前一直不知道构造代码块的意思是什么,只是知道他的具体的表现形式,因为经常在面试题中看到,所以准备好好写写. 作用: 给对象进行初始化,对象一建立就运行,而且优于构造方法运行. 和构造方法的区别 ...

  9. Windows服务时间控件怎么调试

    写了timer,调试的话在构造函数里面把Elapsed方法写成null,null就可以调试了 public PSJCService() { InitializeComponent(); Getuser ...

  10. spring cloud微服务架构 服务提供者和服务消费者

    服务提供者和服务消费者 下面这张表格,简单描述了服务提供者/消费者是什么:   | 名词 | 概念 | | ----- | ----------------------- | | 服务提供者 | 服务 ...