|Most Shared

Jetty Agent tech coding linux jetty
11 Nov 2014at Richmond

This scenario sort of happens often, where one team has ssh access to machines, while other teams possibly hopping through jump-boxes to reach it. Again they are denied ssh access, but only certain ports serving web requests.

For this, a simple embedded Jetty agent running on the machine can execute uploaded shell scripts. Here is the code link. Beware, it is open to abuse, use at your own risk.

Crux of the code..

AgentServer.java

public class AgentServer {
    public static void main(String[] args) throws Exception {
        Server server = new Server(8080);
        server.setHandler(new AgentHandler());
        server.start();
        server.join();
    }
}
    

ShellAction.java

public class ShellAction extends BaseAction {

    @Override
    public String execute(HttpServletRequest request, HttpServletResponse response) {
        String script = request.getParameter("script");
        String output;
        log("running script "+script);
        ProcessBuilder pb = new ProcessBuilder(Action.baseDir + script);
        Process process = null;
        try {
            process = pb.start();
            output = readOutput(process);
            log("process output: " + output);
        } catch (Exception e) {
            e.printStackTrace();
            output = e.getMessage();
            log("process error!!");
        } finally {
            if (process != null) process.destroy();
            log("process stopped");
        }
        Map<String, String> model = new HashMap<>();
        model.put("$output", output);
        return fill(template(), model);
    }

    @Override
    public boolean canHandle(String path) {
        return path.contains("/run");
    }
    @Override
    public String template() {
        return "<body style='font-family:Arial'><h1 style='color:#6495ED'>Ran your script..</h1>" +
            "<h3>Output:</h3><pre>$output</pre></body>";
    }

    private String readOutput(Process process) throws IOException {
        InputStream is = process.getInputStream();
        InputStreamReader isr = new InputStreamReader(is);
        BufferedReader br = new BufferedReader(isr);
        String line;
        StringBuilder builder = new StringBuilder();
        while ((line = br.readLine()) != null)
            builder.append(line).append("\n");
        return builder.toString();
    }
}
    
comments powered by Disqus

All content except noted photos and videos copyright © Vijayaraj Chakravarthy. All rights reserved. *Any images or videos not listed as mine are copyright to their respective owners and were used under creative common license or fair use standards. If a photo or video is your material and you do not wish it to be on the site, please email me vijayrc@outlook.com and I will remove it immediately.