springboot执行shell命令
时间: 2023-10-23 12:36:17 浏览: 41
在 Spring Boot 中执行 shell 命令,可以使用 Java 的 `Runtime` 类或者使用 Apache Commons Exec 库。
1. 使用 `Runtime` 类:
```java
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class ShellCommandExecutor {
public static void main(String[] args) {
try {
String command = "ls -l"; // 要执行的 shell 命令
Process process = Runtime.getRuntime().exec(command);
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
int exitCode = process.waitFor();
System.out.println("Exited with error code : " + exitCode);
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
2. 使用 Apache Commons Exec 库,需要将其添加到 Maven 依赖中:
```xml
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-exec</artifactId>
<version>1.3</version>
</dependency>
```
然后可以使用以下代码执行 shell 命令:
```java
import org.apache.commons.exec.CommandLine;
import org.apache.commons.exec.DefaultExecutor;
import org.apache.commons.exec.ExecuteException;
import org.apache.commons.exec.ExecuteResultHandler;
import org.apache.commons.exec.ExecuteStreamHandler;
import org.apache.commons.exec.Executor;
import org.apache.commons.exec.PumpStreamHandler;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
public class ShellCommandExecutor {
public static void main(String[] args) {
try {
String command = "ls -l"; // 要执行的 shell 命令
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
ByteArrayOutputStream errorStream = new ByteArrayOutputStream();
CommandLine commandLine = CommandLine.parse(command);
ExecuteStreamHandler streamHandler = new PumpStreamHandler(outputStream, errorStream);
Executor executor = new DefaultExecutor();
executor.setStreamHandler(streamHandler);
// 可以使用 ExecuteResultHandler 进行异步执行
//executor.execute(commandLine, new MyExecuteResultHandler());
int exitCode = executor.execute(commandLine);
String output = outputStream.toString();
String error = errorStream.toString();
System.out.println("Output:\n" + output);
System.out.println("Error:\n" + error);
System.out.println("Exited with error code : " + exitCode);
} catch (ExecuteException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
// 异步执行的示例 ExecuteResultHandler
class MyExecuteResultHandler implements ExecuteResultHandler {
@Override
public void onProcessComplete(int exitValue) {
System.out.println("Command executed successfully.");
}
@Override
public void onProcessFailed(ExecuteException e) {
System.err.println("Command execution failed.");
e.printStackTrace();
}
}
```
这样你就可以在 Spring Boot 中执行 shell 命令了。请注意,执行 shell 命令具有一定的安全风险,请谨慎使用,并确保你信任要执行的命令。