java executing bash script

Keywords: Apache Java shell Nginx

Background

Soon after May 1, in order to cope with the online service outage, the leader arranged everyone to take turns on duty. But the server is deployed in the intranet. Even if you know that it is down and want to restart, you can't do without a computer. It's not feasible for us to take computers to travel on May Day. So I want to start a service in the server, map it out through the nginx extranet, then visit the h5 page through the mobile phone, call the background java program, execute the service restart script written in advance, and finish it. Don't talk too much. Start:

2, The program is completed by h5 + bootstrap+springBoot.

  • Front page
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">

    <title>Title</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css"></link>
    <script th:src="@{/md5.js}"></script>
</head>
<body class="container">
<div style="margin-top: 100px;">
    <label>test operation</label>
    <button type="button" class="btn btn-danger" onclick="execShell('test_stop')">Stop it test</button>
    <button type="button" class="btn btn-success" onclick="execShell('test_start')">start-up test</button>

</div>
<div style="margin-top: 20px;">
    <label>8082 operation</label>
    <button type="button" class="btn btn-danger" onclick="execShell('8081_stop')">Stop 8081</button>
    <button type="button" class="btn btn-success" onclick="execShell('8081_start')">Start 8081</button>

</div>
<div style="margin-top: 20px;">
    <label>8082 operation</label>
    <button type="button" class="btn btn-danger" onclick="execShell('8082_stop')">Stop 8082</button>
    <button type="button" class="btn btn-success" onclick="execShell('8082_start')">Start 8082</button>
</div>
<div style="margin-top: 20px;">
    <label>Please enter the verification code:</label><input class="form-control" type="password" id="password"/>
</div>
<script>
    function execShell(flag) {
        var comfigMsg = "";
        if ("test_stop"==flag) {
            comfigMsg="Confirm to stop the test service?"
        } else if ("test_start"==flag) {
            comfigMsg="Confirm to restart the test service?"
        } else if ("8081_stop"==flag) {
            comfigMsg="Confirm to stop 8081 service?"
        } else if ("8081_start"==flag) {
            comfigMsg="Confirm to restart 8081 service?"
        } else if ("8082_stop"==flag) {
            comfigMsg="Confirm to stop 8082 service?"
        } else if ("8082_start"==flag) {
            comfigMsg="Confirm to restart 8082 service?"
        }
        if(window.confirm(comfigMsg)){
            console.log("Determine");
        }else{
            console.log("cancel");
            return false;
        }
        //Create asynchronous object
        var xhr = new XMLHttpRequest();
        //Set request type and url
        //The post request must add a request header or an error will be reported
        xhr.open('post', '/bash/execShell');
        xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        //Send request
        var password = document.getElementById("password").value;
        var md5Password =  hex_md5(password);//MD5 encryption, md5.js download on the Internet by itself
        xhr.send('flag=' + flag + "&password=" + md5Password);
        xhr.onreadystatechange = function () {
            // This step is to determine whether the server responds correctly
            if (xhr.readyState == 4 && xhr.status == 200) {
                console.log(xhr.responseText);
                alert(xhr.responseText);
            }
        };
    }

</script>
</body>
</html>
  • Background java code
package com.eversec.bash;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.InputStreamReader;

@Controller
public class BashController {
    private String key = "hello123!@#";

    @RequestMapping("/shell")
    public String shell(HttpServletRequest request, Model model) {
        String rootPath = request.getContextPath();
        model.addAttribute("ctx", rootPath);
        return "shell/shell";
    }

    @ResponseBody
    @RequestMapping("/execShell")
    public String execShell(String flag, String password) {
        String message = "Successful implementation";
        System.out.println("Execution flag:" + flag);
        if (!Md5Utils.string2MD5(key).equals(password)) {
            message = "Password error";
            System.out.println(message + ":" + flag);
            return message;
        }
        try {
            String shpath = "";
            if ("test_stop".equals(flag)) {
                shpath = "/home/apache-test/bin/stop.sh";
            } else if ("test_start".equals(flag)) {
                shpath = "/home/apache-test/startup.sh";
            } else if ("8081_stop".equals(flag)) {
                shpath = "/home/apache-8081/bin/stop.sh";
            } else if ("8081_start".equals(flag)) {
                shpath = "/home/apache-8081/bin/startup.sh";
            } else if ("8082_stop".equals(flag)) {
                shpath = "/home/apache-8082/bin/stop.sh";
            } else if ("8082_start".equals(flag)) {
                shpath = "/home/apache-8082/bin/startup.sh";
            } else {
                message = "Unrecognized sign";
                System.out.println(message + ":" + flag);
                return message;
            }
            shpath = "/bin/sh " + shpath;
            System.out.println("About to execute script:" + shpath);
            Process ps = Runtime.getRuntime().exec(shpath);
            ps.waitFor();

            BufferedReader br = new BufferedReader(new InputStreamReader(ps.getInputStream()));
            StringBuffer sb = new StringBuffer();
            String line;
            while ((line = br.readLine()) != null) {
                sb.append(line).append("\n");
            }
            String result = sb.toString();
            System.out.println(result);
            message = result;
        } catch (Exception e) {
            e.printStackTrace();
            message = e.getMessage();
        }
        return message;
    }

}
  • MD5Utils.java
package com.eversec.bash;

import java.security.MessageDigest;

public class Md5Utils {
    /***
     * MD5 Add code to generate 32-bit md5 code
     */
    public static String string2MD5(String inStr){
        MessageDigest md5 = null;
        try{
            md5 = MessageDigest.getInstance("MD5");
        }catch (Exception e){
            System.out.println(e.toString());
            e.printStackTrace();
            return "";
        }
        char[] charArray = inStr.toCharArray();
        byte[] byteArray = new byte[charArray.length];

        for (int i = 0; i < charArray.length; i++)
            byteArray[i] = (byte) charArray[i];
        byte[] md5Bytes = md5.digest(byteArray);
        StringBuffer hexValue = new StringBuffer();
        for (int i = 0; i < md5Bytes.length; i++){
            int val = ((int) md5Bytes[i]) & 0xff;
            if (val < 16)
                hexValue.append("0");
            hexValue.append(Integer.toHexString(val));
        }
        return hexValue.toString();

    }

    public static void main(String[] args) {
        System.out.println(string2MD5("123456"));
    }
}
  • stop.sh script to kill the process
#!/bin/sh

pid=$(ps -ef | grep "/home/apache-test" | grep -v grep | awk '{print $2}')
echo $pid
kill -9 $pid
  • startup.sh is the startup file of tomcat

  • Operation effect

Posted by simply on Sun, 29 Mar 2020 08:07:18 -0700