`
isiqi
  • 浏览: 16359407 次
  • 性别: Icon_minigender_1
  • 来自: 济南
社区版块
存档分类
最新评论

Java运行shell脚本

 
阅读更多

利用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(包含有参数的调用)

    在这段代码中,我们创建了一个`Process`对象`ps`,通过`exec()`方法来执行Shell脚本`JZDZ.sh`,并传递了`bankNo`和`dzDate`两个参数。然后,我们通过`ps.waitFor()`等待脚本执行完成,并通过`BufferedReader`读取...

    java运行shell脚本方法示例

    在Java编程中,有时我们需要在程序中执行操作系统级别的任务,比如...总的来说,通过`Runtime.execute`方法和适当的辅助类,我们可以方便地在Java程序中执行Shell脚本,从而实现与操作系统的交互,执行各种系统级任务。

    IDEA中编写并运行shell脚本的实现

    IDEA中编写并运行shell脚本的实现 IDEA中编写并运行shell脚本的实现是指在Integrated Development Environment(IDE)中编写、配置和运行shell脚本的过程。该过程需要安装bashsupport插件,配置插件,安装git软件,...

    Java调用Shell脚本代码

    在Java程序中调用Unix/Linux主机上的Shell命令,并返回相应执行结果。

    java调用shell脚本执行sqlldr与存储过程

    在java代码中调用执行shell脚本,sqlldr导数与使用sqlplus在shell调用执行存储过程。 linux环境中有2个dba的用户:oracle、erm 还有1个web用户:erm 在linux环境中,这三个用户都可以直接在任意目录下执行该shell...

    java调用shell脚本

    Java作为一种跨平台的编程语言,提供了多种方式来调用Shell脚本,实现与操作系统的交互。本文将深入探讨Java如何调用Shell脚本以及相关的知识点。 首先,Java通过Runtime类或ProcessBuilder类可以执行外部程序,...

    shell,bat脚本运行java程序

    下面将详细介绍如何使用shell脚本(适用于Unix/Linux系统)和bat脚本(适用于Windows系统)来运行Java程序。 **shell脚本运行Java程序** 在Unix/Linux环境中,我们可以创建一个.sh文件作为shell脚本来执行Java程序...

    Shell脚本中获取进程ID的方法

    当我在执行shell脚本时,它会启动一个叫子shell的进程。作为主shell的子进程,子shell将shell脚本中的命令作为批处理运行(因此称为“批处理进程”)。 在某些情况下,你也许想要知道运行中的子shell的PID。这个PID...

    android系统中调用shell脚本

    下面我们将深入探讨如何在Android应用中执行shell脚本以及相关知识点。 首先,我们需要理解Android的沙箱机制。每个Android应用都在自己的进程中运行,具有独立的用户ID,这限制了应用之间的相互访问和系统资源的...

    shell脚本启动Java程序测试工程

    在IT行业中,shell脚本是Linux或Unix操作系统中的一种强大工具,用于自动化任务执行和系统管理。当涉及到启动Java应用程序时,shell脚本可以提供一个方便、可重复且灵活的方法。下面我们将深入探讨如何使用shell脚本...

    java调用Shell脚本.doc

    为了确保Shell脚本能被Java程序调用,首先需要确保脚本本身具有执行权限。可以通过以下步骤为脚本添加执行权限: 1. **编辑Shell脚本**: ```bash #!/bin/sh ``` 这一行告诉系统此脚本应使用`/bin/sh`解释器来...

    java调用shell脚本完美封装

    在Java编程中,有时我们需要与操作系统进行交互,执行一些系统级别的任务,比如自动化运维、文件管理等,这时就可能需要用到调用Shell脚本。本文将详细介绍如何在Java中完美封装shell脚本的调用方法,并提供相关的...

    linux shell脚本启动java类

    详细的linux shell脚本启动java代码类。

    Java调用shell脚本

    下面是一个基本的示例,展示如何使用`Runtime`执行shell脚本: ```java try { Process process = Runtime.getRuntime().exec("/path/to/your/script.sh"); int exitCode = process.waitFor(); System.out....

    重启java程序shell脚本

    linux中java项目需要重启一般使用先找到进程杀掉进程,然后找到项目启动,整个过程不算复杂,但是每次都操作一遍太麻烦,我这里把这个过程整理成shell脚本,大家可以修改里面项目名称,每次直接执行这个命令重启项目...

    linux系统java服务自启动shell脚本及服务cpu内存占用监控脚本

    自启动shell脚本和CPU、内存占用监控脚本能确保Java服务在系统启动时自动运行,并实时监测其性能状态,以便及时发现和处理潜在问题。下面将详细介绍这两个方面的内容。 一、Linux系统Java服务自启动shell脚本 自...

    shell 脚本调用Java类

    在IT领域,Shell脚本和Java是两种非常重要的工具,它们各自在不同的场景下发挥着重要...理解如何在Shell环境中正确运行Java程序,以及如何在Shell脚本中控制Java程序的执行,是提高工作效率和系统灵活性的关键技能。

    Java 调用 Shell 命令

    接下来是关键部分——如何使用Java程序来执行Shell脚本。以下是一个具体的实现步骤: 1. **准备Shell脚本**:首先需要有一个已经写好的Shell脚本(例如`sendKondorFile.sh`),该脚本用于完成文件的FTP上传等操作。...

    linux下shell脚本实现数据的导出

    接下来,我们看看Java代码部分,这部分代码是用于执行shell脚本的: ```java String shfilepath = ServletActionContext.getServletContext().getRealPath("/"+"download/shell/backup.sh"); String exp = "sh " + ...

Global site tag (gtag.js) - Google Analytics