java远程调用shell脚本并获取输出信息
时间: 2023-09-05 22:01:17 浏览: 176
Java可以通过使用Runtime类或ProcessBuilder类来远程调用shell脚本并获取输出信息。
使用Runtime类的示例代码如下:
```java
public class RemoteShellDemo {
public static void main(String[] args) {
String command = "ls -l";
try {
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);
}
process.waitFor();
reader.close();
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}
}
```
使用ProcessBuilder类的示例代码如下:
```java
public class RemoteShellDemo {
public static void main(String[] args) {
String command = "ls -l";
try {
ProcessBuilder processBuilder = new ProcessBuilder(command.split(" "));
Process process = processBuilder.start();
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
process.waitFor();
reader.close();
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}
}
```
以上两种方式都可以通过执行shell命令来远程调用shell脚本,并使用BufferedReader来读取输出信息并打印。请注意,读取输出是阻塞的,需要等待命令执行完毕。
当然,在实际应用中,为了远程调用shell脚本,你需要配置好网络连接和权限等,确保能够正常访问并执行远程服务器上的shell脚本。
阅读全文