这是我用来执行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
都不起作用时,我的最终目标是
nginx -s reload
)