java实时获取linux的us和sy_实战:第十篇:使用Java代码获取Linux系统执行命令后的结果...

该博客介绍了如何使用Java代码通过SSH连接到Linux系统,执行命令获取如ulimit、MySQL配置、Redis状态等信息。文章中展示了使用JSch库进行远程命令执行,并解析返回结果的实现方法。
摘要由CSDN通过智能技术生成

需求一:使用Java代码获取Linux系统执行命令后的结果

bb3a3316a6f91e992965a49d278e4587.png

2f5696deac0d404991d34d12374485c2.png

需求二:获取xml节点数据

390d2dab2a5561e87855707c1312f556.png

解答:

import java.io.*;

import java.lang.management.ManagementFactory;

import java.lang.management.MemoryMXBean;

import java.util.*;

import java.util.concurrent.CountDownLatch;

import java.util.regex.Matcher;

import java.util.regex.Pattern;

import com.jcraft.jsch.ChannelExec;

import com.jcraft.jsch.JSch;

import com.jcraft.jsch.JSchException;

import com.jcraft.jsch.Session;

import org.dom4j.Document;

import org.dom4j.DocumentException;

import org.dom4j.Element;

import org.dom4j.io.SAXReader;

import org.dom4j.tree.DefaultAttribute;

import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import org.springframework.util.CollectionUtils;

import org.springframework.util.StringUtils;

import xsf.data.*;

/**

* SSH工具类

* @author

* 2013-4-7

*/

public class TestGetData {

public static void main(String args[]){

}

public static Map getXml(String url){

Map hashMap = new HashMap<>();

//创建解析器

SAXReader saxreader = new SAXReader();

//读取文档

Document doc = null;

try {

doc = saxreader.read(new File(url));

} catch (DocumentException e) {

e.printStackTrace();

}

//获取根

Element root = doc.getRootElement();

//获取子节点

List list = root.elements();

for (Element element : list) {

String name = element.getName();

if("System".equals(name)){

Element dbConnection = element.element("DataBase").element("DBConnection");

String removeAbandoned = dbConnection.attributeValue("removeAbandoned");

hashMap.put("removeAbandoned",removeAbandoned != "" && removeAbandoned != null ? removeAbandoned : "");

String removeAbandonedTimeout = dbConnection.attributeValue("removeAbandonedTimeout");

hashMap.put("removeAbandonedTimeout",removeAbandonedTimeout != "" && removeAbandonedTimeout != null ? removeAbandonedTimeout : "");

String logAbandoned = dbConnection.attributeValue("logAbandoned");

hashMap.put("logAbandoned",logAbandoned != "" && logAbandoned != null ? logAbandoned : "");

}

if("Service".equals(name)){

Element connector = element.element("Connector");

hashMap.put("port",connector.attributeValue("port"));

hashMap.put("protocol",connector.attributeValue("protocol"));

hashMap.put("maxThreads",connector.attributeValue("maxThreads"));

hashMap.put("connectionTimeout",connector.attributeValue("connectionTimeout"));

}

if("ConnectionSettings".equals(name)){

List settings = element.elements("Settings");

for (Element setting : settings) {

String attributeValue = setting.attributeValue("Id");

if("XUGUConnection".equals(attributeValue)){

List elements = setting.elements("Add");

for (Element attr : elements) {

List attributes = attr.attributes();

DefaultAttribute value = (DefaultAttribute) attributes.get(0);

String valueValue = value.getValue();

DefaultAttribute data = (DefaultAttribute) attributes.get(1);

String dataValue = data.getValue();

if("removeAbandoned".equals(valueValue)){

hashMap.put("removeAbandoned",dataValue);

}

if("removeAbandonedTimeout".equals(valueValue)){

hashMap.put("removeAbandonedTimeout",dataValue);

}

if("logAbandoned".equals(valueValue)){

hashMap.put("logAbandoned",dataValue);

}

}

}

}

}

}

return hashMap;

}

//

//

// static ThreadPoolTaskExecutor threadPoolTaskExecutor;

//

// static {

// threadPoolTaskExecutor = new ThreadPoolTaskExecutor();

// threadPoolTaskExecutor.setCorePoolSize(5);

// threadPoolTaskExecutor.setMaxPoolSize(10);

// threadPoolTaskExecutor.setQueueCapacity(100);

// threadPoolTaskExecutor.initialize();

// }

//

// /**

// * 获取数据

// */

// public static List getData(){

// List list = new ArrayList<>();

// if(!"Linux".equals(OSinfo.getOSname())){

// final CountDownLatch latch = new CountDownLatch(5);

// threadPoolTaskExecutor.submit(new Runnable() {

// @Override

// public void run() {

// TestGetData.getJVM();

// latch.countDown();

// }

// });

// threadPoolTaskExecutor.submit(new Runnable() {

// @Override

// public void run() {

// Map linux = TestGetData.getOpenFiles("192.168.134.100", "root", "root", 22, "ulimit -a");

// list.add(linux);

// latch.countDown();

// }

// });

// threadPoolTaskExecutor.submit(new Runnable() {

// @Override

// public void run() {

// Map mysql = TestGetData.getMysql("192.168.134.100", "root", "root", 22, "cat /etc/my.cnf");

// list.add(mysql);

// latch.countDown();

// }

// });

// threadPoolTaskExecutor.submit(new Runnable() {

// @Override

// public void run() {

// Map redis = TestGetData.getRedis("192.168.134.100", "root", "root", 22, "cat redis.conf", "/usr/local/redis/bin/redis-cli info clients");

// list.add(redis);

// latch.countDown();

// }

// });

// threadPoolTaskExecutor.submit(new Runnable() {

// @Override

// public void run() {

Map tomcat = TestGetData.getXml("G:\\Tomcat\\PersonalTomcat\\OrdinaryTomcat\\apache-tomcat-9.0.27\\conf\\server.xml");

list.add(tomcat);

// latch.countDown();

// }

// });

// }

// return list;

// }

//

//

//

// /**

// * 远程 执行命令并返回结果调用过程 是同步的(执行完23才会返回)

// * @param host主机名

// * @param user用户名

// * @param psw密码

// * @param port端口

// * @param command命令

// * @return

// */

// public static Map exec(String host,String user,String psw,int port,String command){

// String result="";

// Session session =null;

// ChannelExec openChannel =null;

// Map map = new HashMap<>();

// try {

// JSch jsch=new JSch();

// session = jsch.getSession(user, host, port);

// java.util.Properties config = new java.util.Properties();

// config.put("StrictHostKeyChecking", "no");

// session.setConfig(config);

// session.setPassword(psw);

// session.connect();

// openChannel = (ChannelExec) session.openChannel("exec");

// openChannel.setCommand(command);

// openChannel.connect();

// InputStream in = openChannel.getInputStream();

// BufferedReader reader = new BufferedReader(new InputStreamReader(in));

// String buf = null;

// while ((buf = reader.readLine()) != null) {

// String data = new String(buf.getBytes("UTF-8"),"UTF-8");

// result+= data +"\r\n";

// if(buf.contains("open files")){

// map.put("openFiles",data);

// }

// if(buf.contains("soft nofile")){

// map.put("softNofile",data);

// }

// if(buf.contains("hard nofile")){

// map.put("hardNofile",data);

// }

// if(buf.contains("max_connections")){

// map.put("maxConnections",data);

// }

// if(buf.contains("innodb_buffer_pool_size")){

// map.put("innodbBufferPoolSize",data);

// }

// if(buf.contains("timeout")){

// map.put("timeout",data);

// }

// if(buf.contains("connected_clients")){

// map.put("connectedClients",data);

// }

// }

// } catch (JSchException | IOException e) {

// result+=e.getMessage();

// }finally{

// if(openChannel!=null&&!openChannel.isClosed()){

// openChannel.disconnect();

// }

// if(session!=null&&session.isConnected()){

// session.disconnect();

// }

// }

// map.put("all",result);

// return map;

// }

//

// public static void getJVM(){

// MemoryMXBean memorymbean = ManagementFactory.getMemoryMXBean();

// System.out.println("堆内存信息: " + memorymbean.getHeapMemoryUsage());

// System.out.println("方法区内存信息: " + memorymbean.getNonHeapMemoryUsage());

//

// List inputArgs = ManagementFactory.getRuntimeMXBean().getInputArguments();

// System.out.println("\n#####################运行时设置的JVM参数#######################");

// System.out.println(inputArgs);

//

// System.out.println("\n#####################运行时内存情况#######################");

// long totle = Runtime.getRuntime().totalMemory();

// System.out.println("总的内存量 [" + totle + "]");

// long free = Runtime.getRuntime().freeMemory();

// System.out.println("空闲的内存量 [" + free + "]");

// long max = Runtime.getRuntime().maxMemory();

// System.out.println("最大的内存量 [" + max + "]");

// }

//

//

//

// public static Map getRedis(String host,String user,String psw,int port,String conf,String info){

// Map map = exec(host, user, psw, port, conf);//"cat redis.conf"

// Map hashMap = new HashMap<>();

// if(!CollectionUtils.isEmpty(map)){

// String timeoutStr = (String) map.get("timeout");

// if(!StringUtils.isEmpty(timeoutStr)){

// hashMap.put("timeout ",timeoutStr);

// }else {

// hashMap.put("timeout ","0");

// }

// }

// Map clients = exec(host, user, psw, port, info);//"/usr/local/redis/bin/redis-cli info clients"

// String connectedClients = getInt(((String)clients.get("connectedClients")));

// hashMap.put("connectedClients",connectedClients);

// return hashMap;

// }

//

// /**

// * 获取mysql参数

// * @return

// */

// public static Map getMysql(String host,String user,String psw,int port,String command){

// Map map = exec(host, user, psw, port, command);//"cat /etc/my.cnf"

// Map hashMap = new HashMap<>();

// if(!CollectionUtils.isEmpty(map)){

// String maxConnections = getInt(((String)map.get("maxConnections")));

// if(StringUtils.isEmpty(maxConnections)){

// maxConnections = "0";

// hashMap.put("maxConnections",maxConnections);

// }

// String innodbBufferPoolSize = getInt((String)map.get("innodbBufferPoolSize"));

// if(StringUtils.isEmpty(innodbBufferPoolSize)){

// innodbBufferPoolSize = "0";

// hashMap.put("innodbBufferPoolSize",innodbBufferPoolSize);

// }

// }

// return hashMap;

// }

//

// /**

// * 获取打开的最大文件数

// * @return

// */

// public static Map getOpenFiles(String host,String user,String psw,int port,String ulimit){

// Map hashMap = new HashMap<>();

// Map map = exec(host, user, psw, port, ulimit);//ulimit -a

// String openFiles = (String) map.get("openFiles");

// hashMap.put("openFiles",openFiles);

// return hashMap;

// }

//

// /**

// * 获取nofile

// * @param host

// * @param user

// * @param psw

// * @param port

// * @param noFile

// * @return

// */

// public static Map getNofile(String host,String user,String psw,int port,String noFile){

// Map hashMap = new HashMap<>();

// Map exec = exec(host, user, psw, port, noFile);//"cat /etc/security/limits.conf"

// String hardNofile = getInt((String)exec.get("hardNofile"));

// hashMap.put("hardNofile",hardNofile);

// String softNofile = getInt((String)exec.get("softNofile"));

// hashMap.put("softNofile",softNofile);

// return hashMap;

// }

//

// /**

// * 获取数字

// * @param str

// * @return

// */

// private static String getInt(String str){

// String regEx="[^0-9]";

// Pattern p = Pattern.compile(regEx);

// Matcher m = p.matcher(str);

// return m.replaceAll("").trim();

// }

}

pom.xml

com.jcraft

jsch

0.1.46

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值