sd.code.stagent.services.Shell.java Source code

Java tutorial

Introduction

Here is the source code for sd.code.stagent.services.Shell.java

Source

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package sd.code.stagent.services;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import sd.code.stagent.common.ProcessWithWait;
import sd.code.stagent.common.Web;

/**
 *
 * @author motaz
 */
@WebServlet(name = "Shell", urlPatterns = { "/Shell" })
public class Shell extends HttpServlet {

    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        try (PrintWriter out = response.getWriter()) {
            String requestText = Web.readClient(request);
            try {

                JSONParser parser = new JSONParser();
                JSONObject obj = (JSONObject) parser.parse(requestText);
                String command = obj.get("command").toString();

                String everything;
                if (command.contains("|")) {
                    everything = executeShell(command);
                } else {
                    everything = executeShell(command, 30000);
                }

                obj.put("success", true);
                obj.put("errorcode", 0);
                obj.put("result", everything);
                out.println(obj.toJSONString());
            } catch (Exception ex) {
                JSONObject result = new JSONObject();
                result.put("success", false);
                result.put("errorcode", 5);
                result.put("message", ex.toString());

                out.println(result.toJSONString());
            }

        }
    }

    public static String executeShell(String command) throws InterruptedException, IOException {

        Process pp = Runtime.getRuntime().exec(new String[] { "/bin/sh", "-c", command });
        pp.waitFor();
        BufferedReader reader = new BufferedReader(new InputStreamReader(pp.getInputStream()));
        String line;
        String everything = "";
        while ((line = reader.readLine()) != null) {
            everything = everything + line + "\n";
        }
        return everything;
    }

    public static String executeShell(String command, int waitTime) throws IOException {
        Process process = Runtime.getRuntime().exec(command);
        ProcessWithWait processWithWait = new ProcessWithWait(process);
        int exitCode = processWithWait.waitForProcess(waitTime);

        String result = "";
        if (exitCode == Integer.MIN_VALUE) {
            result = "Timeout: "; // Timeout
            process.destroy();
        } else {

            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line;

            while ((line = reader.readLine()) != null) {
                result = result + line + "\n";
            }
        }

        return result;
    }

    public static void main(String a[]) throws InterruptedException, IOException {

        System.out.println(executeShell("uptime"));

    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}