练习1:使用java实现Linux后台程序运行状态实时显示

大致流程:

image-20220124115324901

idea连接linux

首先下载jar包:ganymed-ssh2-build210.jar

image-20220124092128252

新建java项目,将jar包导入到lib中

image-20220124092340887

连接代码:

package com.wang.data;

import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class Input {
    public static void main(String[] args) {
            String hostname = "192.168.115.130";
            String username = "root";
            String password = "201314";

            Connection conn = new Connection(hostname);
            Session ssh = null;
            try {
                conn.connect();
                conn.authenticateWithPassword(username, password);
                ssh = conn.openSession();
                ssh.execCommand("pwd;jps");
                InputStream is = new StreamGobbler(ssh.getStdout());
                BufferedReader brs = new BufferedReader(new InputStreamReader(is));
                while(true){
                    String line = brs.readLine();
                    if(line==null){
                        break;
                    }
                    System.out.println(line);
                }
                ssh.close();
                conn.close();
            } catch (IOException e) {
// TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
}

运行结果:

image-20220124094851430

对上述代码进行封装:

新建db.properties,用以存放linux系统的hostname,username,password

hostname = 192.168.115.130
username = root
password = 201314

新建LinuxUtils.class,对连接代码进行封装

package com.wang.utils;

import ch.ethz.ssh2.Connection;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class LinuxUtils {
    private static String hostname = null;
    private static String username = null;
    private static String password = null;

    static {
        try {
            InputStream in = LinuxUtils.class.getClassLoader().getResourceAsStream("db.properties");
            Properties properties = new Properties();
            properties.load(in);
            hostname = properties.getProperty("hostname");
            username = properties.getProperty("username");
            password = properties.getProperty("password");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static Connection getConnection() throws IOException {
        Connection conn = new Connection(hostname);
        conn.connect();
        conn.authenticateWithPassword(username, password);
        return conn;
    }
}

封装后的Input代码:

package com.wang.data;

import com.wang.utils.LinuxUtils;
import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class Input {
    public static void main(String[] args) {

        Connection conn = null;
        Session ssh = null;
        try {
            conn = LinuxUtils.getConnection();
            ssh = conn.openSession();
            ssh.execCommand("pwd;jps");
            InputStream is = new StreamGobbler(ssh.getStdout());
            BufferedReader brs = new BufferedReader(new InputStreamReader(is));
            while (true) {
                String line = brs.readLine();
                if (line == null) {
                    break;
                }
                System.out.println(line);
            }
            ssh.close();
            conn.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

完成!

处理返回结果

将发送给Linux的命令更改为ps -ef|grep TimelyWharfJobMain |grep -v grep,得到返回结果:

image-20220124100841403

修改Input,返回pid和ppid

package com.wang.data;

import com.wang.utils.LinuxUtils;
import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class Input {
    public static String test(){
        String a = null;String b = null;
        Connection conn = null;
        Session ssh = null;
        try {
            conn = LinuxUtils.getConnection();
            ssh = conn.openSession();
            ssh.execCommand("ps -ef|grep TimelyWharfJobMain |grep -v grep");
            InputStream is = new StreamGobbler(ssh.getStdout());
            BufferedReader brs = new BufferedReader(new InputStreamReader(is));
            while (true) {
                String line = brs.readLine();
                if (line == null) {
                    break;
                }
                a=line.substring(9,15);
                b=line.substring(16,22);
            }
            ssh.close();
            conn.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return a+b;
    }
}

创建数据库连接

下载jar包:mysql-connector-java-8.0.26.jar,导入到lib中:

image-20220124102602280

直接封装。新建mysqldb.properties:

driver=com.mysql.cj.jdbc.Driver
url = jdbc:mysql://localhost:3306/bank?userUnicode=true&characterEncoding=utf8&useSSL=true&serverTimezone=Hongkong
username = root
password = 201314

创建JdbcUtils.class

package com.wang.utils;

import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

public class JdbcUtils {
    private static String url = null;
    private static String username = null;
    private static String password = null;

    static {
        try {
            InputStream in = JdbcUtils.class.getClassLoader().getResourceAsStream("mysqldb.properties");
            Properties properties = new Properties();
            properties.load(in);

            String dirver = properties.getProperty("driver");
            url = properties.getProperty("url");
            username = properties.getProperty("username");
            password = properties.getProperty("password");
            //驱动只用加载一次
            Class.forName(dirver);

        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
    //获取连接
    public static Connection getConnection() throws SQLException {
        return DriverManager.getConnection(url, username, password);
    }
    //释放资源
    public static void release(Connection conn, Statement st, ResultSet rs){
        if(rs!=null){
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(st!=null){
            try {
                st.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(conn!=null){
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}

新建数据库:

image-20220124104114835

创建完成。

image-20220124104228205

新建InsertData向数据库中插入数据

package com.wang.data;

import com.wang.utils.JdbcUtils;
import java.util.Date;
import java.sql.*;
import static com.wang.data.Input.*;

public class InsertData {

    public static void main(String[] args) {
        String s1 = test();	
        
        Connection conn = null;
        PreparedStatement st = null;
        try {
            conn = JdbcUtils.getConnection();
            String sql = "insert into user(name,pid,ppid,status,date) value(?,?,?,?,?)";
            st = conn.prepareStatement(sql);//预编译SQl,先写sql,然后不执行

            st.setString(1,"TimelyWharfJobMain");
            st.setString(2,s1.substring(0,6));
            st.setString(3,s1.substring(6,12));
            st.setString(4,"fail");
            st.setString(5, String.valueOf(new java.sql.Date(new Date().getTime())));
            st.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            JdbcUtils.release(conn,st,null);
        }
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

运行结果:

image-20220124105526371

插入成功!!

实现自动检测

在使用ps语句时,如果程序没有运行,则无任何的返回值,且ssh对象只能使用一次execCommand这个方法。所以每次在检测程序是否运行时,都需要重新连接一次linux。这里假定检测linux系统后台10个程序的运行情况:

package com.wang.data;

import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;
import com.wang.utils.LinuxUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class Input {

    public static String test01(){
        String a1 = null;String b1 = null;
        //预设a1、bi值为null,若程序未启动无返回值时,则a1+b1=nullnull,以此判断程序是否在运行
        Connection conn = null;Session ssh = null;

        try {
            conn = LinuxUtils.getConnection();
            ssh = conn.openSession();
            ssh.execCommand("ps -ef|grep TimelyWharfJobMain |grep -v grep");
            InputStream is = new StreamGobbler(ssh.getStdout());
            BufferedReader brs = new BufferedReader(new InputStreamReader(is));
            while (true) {
                String line = brs.readLine();
                if (line == null) {
                    break;
                }
                a1=line.substring(9,15);b1=line.substring(16,22);
            }
            ssh.close();
            conn.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return a1+b1;
    }
    
    public static String test02(){...}
    
    public static String test03(){...}
    
    public static String test04(){...}
    
    public static String test05(){...}
    
    public static String test06(){...}
    
    public static String test07(){...}
    
    public static String test08(){...}
    
    public static String test09(){...}
    
    public static String test09(){...}
    
    public static String test10(){...}
}

test02到test10代码与test01相同,也可添加一些错误命令试验。

同时,InsertData:

package com.wang.data;

import com.wang.utils.JdbcUtils;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.sql.*;
import static com.wang.data.Input.*;

public class InsertData {
    public void insertData(){
        String s1 =test01();
        String s2 =test02();
        String s3 =test03();
        String s4 =test04();
        String s5 =test05();
        String s6 =test06();
        String s7 =test07();
        String s8 =test08();
        String s9 =test09();
        String s10 =test10();
        String[] a={s1,s2,s3,s4,s5,s6,s7,s8,s9,s10};
        String[] b={"01","02","03","04","05","06","07","08","09","10"};

        for (int i = 0; i < 10; i++) {
            Connection conn = null;
            PreparedStatement st = null;
            Date Now = new Date( );
            SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
            try {
                conn = JdbcUtils.getConnection();

                String sql = "insert into user(name,pid,ppid,status,date) value(?,?,?,?,?)";
                st = conn.prepareStatement(sql);//预编译SQl,先写sql,然后不执行

                st.setString(1,b[i]);
                if(a[i].length()==12){
                    st.setString(2,a[i].substring(0,6));
                    st.setString(3,a[i].substring(6,12));
                    st.setString(4,"success");
                }else if(a[i].length()==8){
                    st.setString(2,a[i].substring(0,4));
                    st.setString(3,a[i].substring(4,8));
                    st.setString(4,"fail");
                }
                st.setString(5,ft.format(Now));
                st.executeUpdate();
            } catch (SQLException e) {
                e.printStackTrace();
            }finally {
                JdbcUtils.release(conn,st,null);
            }
            try {
                Thread.sleep(1000);	//1s插入1条数据
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

主程序demo:

package com.wang.data;

public class demo {
    public static void main(String[] args) throws InterruptedException {
        while (ture) {
            InsertData insertData = new InsertData();
            insertData.insertData();
            Thread.sleep(20000);	//20s刷新一次
        }
    }
}

程序结构如下:

image-20220124135656766

运行结果:

image-20220126152904764

数据库各字段含义:id用以排序,name程序名称,有pidppid时,程序status为success,date为当前时间。

读取数据

新建一个空的maven项目,具体可参考javaweb-01 - 萘汝 - 博客园 (cnblogs.com)中的4.2-在IDEA中使用maven。

image-20220124141840270

web.xml:替换为webapp4.0版本,和tomcat一致

<?xml version="1.0" encoding="UTF-8"?>
        
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
                      http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
  version="4.0"
  metadata-complete="true">
 
</web-app>

pom.xml文件中添加依赖:

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.wang</groupId>
  <artifactId>web</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>war</packaging>

  <dependencies>
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>4.0.1</version>
    </dependency>
    <dependency>
      <groupId>javax.servlet.jsp</groupId>
      <artifactId>javax.servlet.jsp-api</artifactId>
      <version>2.3.3</version>
    </dependency>
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>8.0.26</version>
    </dependency>

  </dependencies>

<!--  在bulid中配置resources,来防止我们资源导出失败问题-->
  <build>
    <resources>
      <resource>
        <directory>src/main/resources</directory>
        <includes>
          <include>**/*.properties</include>
          <include>**/*.xml</include>
        </includes>
      </resource>
      <resource>
        <directory>src/main/java</directory>
        <includes>
          <include>**/*.properties</include>
          <include>**/*.xml</include>
        </includes>
        <filtering>true</filtering>
      </resource>
    </resources>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <configuration>
          <source>7</source>
          <target>7</target>
        </configuration>
      </plugin>
    </plugins>
  </build>

</project>

运行Tomcat:

image-20220124143915171

maven创建完成。

首先是Bean:

package com.wang.servlet;

public class Bean {
    private String name=null;
    private String pid=null;
    private String ppid=null;
    private String status=null;
    private String date=null;

    public Bean(){
    }

    public Bean(String name, String pid, String ppid, String status, String date) {
        this.name = name;
        this.pid = pid;
        this.ppid = ppid;
        this.status = status;
        this.date = date;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPid() {
        return pid;
    }

    public void setPid(String pid) {
        this.pid = pid;
    }

    public String getPpid() {
        return ppid;
    }

    public void setPpid(String ppid) {
        this.ppid = ppid;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public String getDate() {
        return date;
    }

    public void setDate(String date) {
        this.date = date;
    }
}

访问数据库,BeanDao:

package com.wang.servlet;

import com.wang.utils.JdbcUtils;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class BeanDao {
    public List<Bean> find(){
        List<Bean> list=new ArrayList<Bean>();//创建bean的链表,用来接收数据

            Connection conn = null;
            PreparedStatement st = null;ResultSet rs=null;
            try {
                conn = JdbcUtils.getConnection();
                String sql = "select name,pid,ppid,status,date from user order by id desc limit 10";
                st = conn.prepareStatement(sql);//预编译SQl,先写sql,然后不执行
                rs=st.executeQuery();//取结果集

                while(rs.next()) {
                    Bean i=new Bean();//用bean创建对象,将取出来的数据封装到在里面
                    i.setName(rs.getString(1));
                    i.setPid(rs.getString(2));
                    i.setPpid(rs.getString(3));
                    i.setStatus(rs.getString(4));
                    i.setDate(rs.getString(5));
                    list.add(i);//将封装的数据加到先前创建的list里
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }finally {
                JdbcUtils.release(conn,st,null);
            }
        return list;
    }
}

显示到web页面

TestServlet:

package com.wang.servlet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

public class TestServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
        BeanDao dao = new BeanDao();
        List<Bean> list = dao.find();
        req.setAttribute("beans", list);
        req.getRequestDispatcher("/test.jsp").forward(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }
}

在web.xml中注册TestServlet:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
                      http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0"
         metadata-complete="true">
    <!--    注册Servlet-->
    <servlet>
        <servlet-name>hello</servlet-name>
        <servlet-class>com.wang.servlet.TestServlet</servlet-class>
    </servlet>
    <!--    Servlet的请求路径-->
    <servlet-mapping>
        <servlet-name>hello</servlet-name>
        <url-pattern>/hello</url-pattern>
    </servlet-mapping>
</web-app>

最后是展示页面test.jsp:

<%@ page import="com.wang.servlet.Bean" %>
<%@ page import="java.util.List" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<%--    5s自动刷新--%>
    <meta http-equiv="refresh" content="5">

    <style>
        #layui-title{
            text-align: center;
        }
        #layui-button{
            text-align: center;
        }
    </style>

</head>
<body>

<div id="layui-title">
    <h1>Linux程序运行状态实时显示</h1>
</div>

<div id="layui-container">
    <table id="layui-table" border="1px" width="700px" align="center" >
        <thead>
        <tr>
            <th>name</th><th>pid</th><th>ppid</th><th>status</th><th>date</th>
        </tr>
        </thead>

        <tbody>
        <%
            List<Bean> list =(List<Bean>)request.getAttribute("beans");
            for(Bean i:list){
        %>
        <tr>
            <td><%=i.getName() %></td>
            <td><%=i.getPid() %></td>
            <td><%=i.getPpid()%></td>
            <td><%=i.getStatus()%></td>
            <td><%=i.getDate()%></td>
        </tr>
        <%
            }
        %>
        </tbody>

    </table>
</div>

<div id="layui-button" >
    <Button onclick="location.reload()">刷新</Button>
    <Button onclick="window.location='test02.jsp'">记录</Button>
    <Button onclick="window.location='index.jsp'">退出</Button>
</div>

</body>
</html>

运行结果:

image-20220126153721201

查看记录功能

BeanDao2:

package com.wang.servlet;

import com.wang.utils.JdbcUtils;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class BeanDao2 {
    public List<Bean> find(){
        List<Bean> list=new ArrayList<Bean>();//创建bean的链表,用来接收数据

        Connection conn = null;
        PreparedStatement st = null;ResultSet rs=null;
        try {
            conn = JdbcUtils.getConnection();
            String sql = "select name,pid,ppid,status,date from user where status='fail'";
            st = conn.prepareStatement(sql);//预编译SQl,先写sql,然后不执行
            rs=st.executeQuery();//取结果集

            while(rs.next()) {
                Bean i=new Bean();//用bean创建对象,将取出来的数据封装到在里面
                i.setName(rs.getString(1));
                i.setPid(rs.getString(2));
                i.setPpid(rs.getString(3));
                i.setStatus(rs.getString(4));
                i.setDate(rs.getString(5));
                list.add(i);//将封装的数据加到先前创建的list里
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            JdbcUtils.release(conn,st,null);
        }
        return list;
    }
}

test2.jsp:

<%@ page import="java.util.List" %>
<%@ page import="com.wang.servlet.BeanDao2" %>
<%@ page import="com.wang.servlet.Bean" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <style>
        #layui-title{
            text-align: center;
        }
    </style>
</head>
<body>

<div id="layui-title">
    <h2>运行失败记录</h2>
</div>

<div id="layui-container">

    <table id="layui-table" border="1px" width="700px" align="center" >
        <thead>
        <tr>
            <th>name</th><th>pid</th><th>ppid</th><th>status</th><th>date</th>
        </tr>
        </thead>

        <tbody>
        <%
            BeanDao2 dao = new BeanDao2();
            List<Bean> list = dao.find();
            for(Bean i:list){
        %>
        <tr>
            <td><%=i.getName() %></td>
            <td><%=i.getPid() %></td>
            <td><%=i.getPpid()%></td>
            <td><%=i.getStatus()%></td>
            <td><%=i.getDate()%></td>
        </tr>
        <%
            }
        %>
        </tbody>

    </table>
</div>

</body>
</html>

运行结果:

image-20220125093908407

目录结构如下:

image-20220126145424031

posted @ 2022-01-26 16:06  萘汝  阅读(386)  评论(0编辑  收藏  举报
我发了疯似的祝你好!