Java运行shell脚本

本文介绍了一种利用Java的Runtime类执行Linux Shell命令的方法,并提供了一个CommandHelper工具类来简化这一过程。该工具支持设置命令执行超时,同时能够捕获并返回命令的标准输出和错误输出。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

利用Runtime.execute方法,我们可以在Java程序中运行Linux的Shell脚本,或者执行其他程序。参考了互联网上的这篇文章:http://lee79.javaeye.com/blog/418549(感谢一下),我重新整理了代码。
现在通过CommandHelper.execute方法可以执行命令,该类实现代码如下:
package javaapplication3;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
*
* @author chenshu
*/
public class CommandHelper {

//default time out, in millseconds
public static int DEFAULT_TIMEOUT;
public static final int DEFAULT_INTERVAL = 1000;
public static long START;


public static CommandResult exec(String command) throws IOException, InterruptedException {
Process process = Runtime.getRuntime().exec(command);
CommandResult commandResult = wait(process);
if (process != null) {
process.destroy();
}
return commandResult;
}

private static boolean isOverTime() {
return System.currentTimeMillis() - START >= DEFAULT_TIMEOUT;
}

private static CommandResult wait(Process process) throws InterruptedException, IOException {
BufferedReader errorStreamReader = null;
BufferedReader inputStreamReader = null;
try {
errorStreamReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
inputStreamReader = new BufferedReader(new InputStreamReader(process.getInputStream()));

//timeout control
START = System.currentTimeMillis();
boolean isFinished = false;

for (;;) {
if (isOverTime()) {
CommandResult result = new CommandResult();
result.setExitValue(CommandResult.EXIT_VALUE_TIMEOUT);
result.setOutput("Command process timeout");
return result;
}

if (isFinished) {
CommandResult result = new CommandResult();
result.setExitValue(process.waitFor());

//parse error info
if (errorStreamReader.ready()) {
StringBuilder buffer = new StringBuilder();
String line;
while ((line = errorStreamReader.readLine()) != null) {
buffer.append(line);
}
result.setError(buffer.toString());
}

//parse info
if (inputStreamReader.ready()) {
StringBuilder buffer = new StringBuilder();
String line;
while ((line = inputStreamReader.readLine()) != null) {
buffer.append(line);
}
result.setOutput(buffer.toString());
}
return result;
}

try {
isFinished = true;
process.exitValue();
} catch (IllegalThreadStateException e) {
// process hasn't finished yet
isFinished = false;
Thread.sleep(DEFAULT_INTERVAL);
}
}

} finally {
if (errorStreamReader != null) {
try {
errorStreamReader.close();
} catch (IOException e) {
}
}

if (inputStreamReader != null) {
try {
inputStreamReader.close();
} catch (IOException e) {
}
}
}
}
}

CommandHelper类使用了CommandResult对象输出结果错误信息。该类实现代码如下:
package javaapplication3;
/**
*
* @author chenshu
*/
public class CommandResult {
public static final int EXIT_VALUE_TIMEOUT=-1;

private String output;

void setOutput(String error) {
output=error;
}

String getOutput(){
return output;
}

int exitValue;

void setExitValue(int value) {
exitValue=value;
}

int getExitValue(){
return exitValue;
}

private String error;

/**
* @return the error
*/
public String getError() {
return error;
}

/**
* @param error the error to set
*/
public void setError(String error) {
this.error = error;
}
}


现在看看调用代码的演示(main函数接受一个超时参数):
public static void main(String[] args) {
try {
int timeout = Integer.parseInt(args[0]);
CommandHelper.DEFAULT_TIMEOUT = timeout;
CommandResult result = CommandHelper.exec("mkdir testdir");
if (result != null) {
System.out.println("Output:" + result.getOutput());
System.out.println("Error:" + result.getError());
}
} catch (IOException ex) {
System.out.println("IOException:" + ex.getLocalizedMessage());
} catch (InterruptedException ex) {
System.out.println("InterruptedException:" + ex.getLocalizedMessage());
}
}

结果会创建一个testdir目录。

我尝试用这种方法创建通过ssh登录到远程机器,遇到两个问题:
1)如果希望没有人机对话方式,则需要使用命令sshpass -p password ssh user@targetIP 'command'
2) 在NetBeans上直接运行工程是不行的,因为权限不够,需要在终端里运行java javaapplication3.Main
3) 很多命令不能运行,只有如pwd等命令可以运行,原因还不清楚,最好改用Ganymed SSH-2库或者其他类似Java库,我会在下一篇文章中介绍如何使用。








Java中执行Shell脚本可以使用`Runtime`类或`ProcessBuilder`类。下面是使用`Runtime`类执行Shell脚本的示例代码: ```java import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class ShellScriptExecutor { public static void main(String[] args) { try { // 执行Shell脚本命令 String command = "sh /path/to/script.sh"; Process process = Runtime.getRuntime().exec(command); // 获取Shell脚本输出结果 BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream())); String line; while ((line = reader.readLine()) != null) { System.out.println(line); } // 等待Shell脚本执行完成 int exitCode = process.waitFor(); System.out.println("Shell脚本执行完成,退出码:" + exitCode); } catch (IOException | InterruptedException e) { e.printStackTrace(); } } } ``` 上述代码中,`/path/to/script.sh`是你要执行的Shell脚本的路径。你可以将实际的Shell脚本路径替换到代码中。 使用`ProcessBuilder`类执行Shell脚本的示例代码如下: ```java import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class ShellScriptExecutor { public static void main(String[] args) { try { // 执行Shell脚本命令 ProcessBuilder processBuilder = new ProcessBuilder("sh", "/path/to/script.sh"); Process process = processBuilder.start(); // 获取Shell脚本输出结果 BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream())); String line; while ((line = reader.readLine()) != null) { System.out.println(line); } // 等待Shell脚本执行完成 int exitCode = process.waitFor(); System.out.println("Shell脚本执行完成,退出码:" + exitCode); } catch (IOException | InterruptedException e) { e.printStackTrace(); } } } ``` 同样,你需要将实际的Shell脚本路径替换到代码中。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值