在Java中执行特权Shell命令

时间:2019-06-13 20:36:04

标签: java linux bash shell

这是我用来执行Shell命令的简单代码:

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

@RestController
public class ShellController {

    @RequestMapping(value = "/shell", method = RequestMethod.POST)
    public Response postFile(@RequestParam(value = "command") String command) {
        try {
            boolean isWindows = System.getProperty("os.name")
                    .toLowerCase().startsWith("windows");
            ProcessBuilder builder = new ProcessBuilder();
            if (isWindows) {
                builder.directory(new File(System.getProperty("user.home")));
                builder.command("cmd.exe", "/c", command);
            } else {
                builder.directory(new File(System.getenv("HOME")));
                builder.command("sh", "-c", command);
            }
            Process process = builder.start();
            StringConsumer consumer = new StringConsumer();
            StreamGobbler streamGobbler =
                    new StreamGobbler(process.getInputStream(), consumer);
            Executors.newSingleThreadExecutor().submit(streamGobbler);
//          int exitCode = process.waitFor();
//          assert exitCode == 0;
            if(process.waitFor(3, TimeUnit.SECONDS)) {
                return new Response(0, consumer.getConsumed());

            }
            return new Response(-1, consumer.getConsumed());
        } catch (Exception e) {
            return new Response(-1, e.getMessage());
        }
    }

}

此程序的Windows操作系统执行正常,但从Linux操作系统运行时无法正常运行,这是示例端点:

http://127.0.0.1:8686/shell?command="ls"

问题是,当运行mkdir甚至rm都不起作用时,我的最终目标是

  • 将文件写入受sudo限制的路径
  • 删除给定路径(sudo)的文件
  • 执行命令以启动/停止服务器(例如nginx -s reload

0 个答案:

没有答案