实战:第十篇:使用Java代码获取Linux系统执行命令后的结果

本文涉及的产品
Redis 开源版,标准版 2GB
推荐场景:
搭建游戏排行榜
云数据库 RDS MySQL,集群系列 2核4GB
推荐场景:
搭建个人博客
云数据库 Tair(兼容Redis),内存型 2GB
简介: 实战:第十篇:使用Java代码获取Linux系统执行命令后的结果

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




需求二:获取xml节点数据


解答:

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<String, String> 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<Element> 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<Element> settings = element.elements("Settings");
                for (Element setting : settings) {
                    String attributeValue = setting.attributeValue("Id");
                    if("XUGUConnection".equals(attributeValue)){
                        List<Element> elements = setting.elements("Add");
                        for (Element attr : elements) {
                            List<Object> 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<Map> getData(){
//        List<Map> 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<String, String> 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<String> 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<String, String> 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<String, String> 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<String, String> 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<String, String> 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

<!--远程连接linux建立SSH连接-->
<dependency>
    <groupId>com.jcraft</groupId>
    <artifactId>jsch</artifactId>
    <version>0.1.46</version>
</dependency>
相关实践学习
Github实时数据分析与可视化
基于Github Archive公开数据集,将项目、行为等20+种事件类型数据实时采集至Hologres进行分析,并搭建可视化大屏。
阿里云实时数仓实战 - 项目介绍及架构设计
课程简介 1)学习搭建一个数据仓库的过程,理解数据在整个数仓架构的从采集、存储、计算、输出、展示的整个业务流程。 2)整个数仓体系完全搭建在阿里云架构上,理解并学会运用各个服务组件,了解各个组件之间如何配合联动。 3&nbsp;)前置知识要求 &nbsp; 课程大纲 第一章&nbsp;了解数据仓库概念 初步了解数据仓库是干什么的 第二章&nbsp;按照企业开发的标准去搭建一个数据仓库 数据仓库的需求是什么 架构 怎么选型怎么购买服务器 第三章&nbsp;数据生成模块 用户形成数据的一个准备 按照企业的标准,准备了十一张用户行为表 方便使用 第四章&nbsp;采集模块的搭建 购买阿里云服务器 安装 JDK 安装 Flume 第五章&nbsp;用户行为数据仓库 严格按照企业的标准开发 第六章&nbsp;搭建业务数仓理论基础和对表的分类同步 第七章&nbsp;业务数仓的搭建&nbsp; 业务行为数仓效果图&nbsp;&nbsp;
相关文章
|
5天前
|
Java
java小工具util系列4:基础工具代码(Msg、PageResult、Response、常量、枚举)
java小工具util系列4:基础工具代码(Msg、PageResult、Response、常量、枚举)
17 5
|
3天前
|
Java 开发者
探索Java中的Lambda表达式:简化你的代码之旅##
【8月更文挑战第62天】 Java 8的发布为开发者带来了诸多新特性,其中最引人注目的无疑是Lambda表达式。这一特性不仅让代码变得更加简洁,还极大地提升了开发的效率。本文将通过实际示例,展示如何利用Lambda表达式来优化我们的代码结构,同时探讨其背后的工作原理和性能考量。 ##
|
6天前
|
Java API 开发者
探索Java中的Lambda表达式:简化代码,提升效率
【9月更文挑战第27天】在Java 8中引入的Lambda表达式为编程带来了革命性的变化。通过简洁的语法和强大的功能,它不仅简化了代码编写过程,还显著提升了程序的执行效率。本文将深入探讨Lambda表达式的本质、用法和优势,并结合实例演示其在实际开发中的应用。无论你是Java新手还是资深开发者,都能从中获得启发,优化你的代码设计。
|
6天前
|
存储 Java 索引
使用java代码实现左右括号查找
使用java代码实现左右括号查找
|
4天前
|
Java 数据中心 微服务
Java高级知识:线程池隔离与信号量隔离的实战应用
在Java并发编程中,线程池隔离与信号量隔离是两种常用的资源隔离技术,它们在提高系统稳定性、防止系统过载方面发挥着重要作用。
6 0
|
5天前
|
安全 Java 调度
Java编程时多线程操作单核服务器可以不加锁吗?
Java编程时多线程操作单核服务器可以不加锁吗?
18 2
|
9天前
|
存储 缓存 Java
java线程内存模型底层实现原理
java线程内存模型底层实现原理
java线程内存模型底层实现原理
|
19天前
|
存储 缓存 安全
【Java面试题汇总】多线程、JUC、锁篇(2023版)
线程和进程的区别、CAS的ABA问题、AQS、哪些地方使用了CAS、怎么保证线程安全、线程同步方式、synchronized的用法及原理、Lock、volatile、线程的六个状态、ThreadLocal、线程通信方式、创建方式、两种创建线程池的方法、线程池设置合适的线程数、线程安全的集合?ConcurrentHashMap、JUC
【Java面试题汇总】多线程、JUC、锁篇(2023版)
|
13天前
|
缓存 Java 应用服务中间件
Java虚拟线程探究与性能解析
本文主要介绍了阿里云在Java-虚拟-线程任务中的新进展和技术细节。
|
11天前
|
Java 开发者
Java中的多线程基础与应用
【9月更文挑战第22天】在Java的世界中,多线程是一块基石,它支撑着现代并发编程的大厦。本文将深入浅出地介绍Java中多线程的基本概念、创建方法以及常见的应用场景,帮助读者理解并掌握这一核心技术。
下一篇
无影云桌面