java 调用shell 执行命令的方法总结

方案1、通过java程序直接调用shell

实现方式一、使用自带的 使用到Process和Runtime两个类,返回值通过Process类的getInputStream()方法获取

参考 http://blog.csdn.net/arkblue/article/details/7897396

package ark;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

public class ReadCmdLine {
    public static void main(String args[]) {
        Process process = null;
        List<String> processList = new ArrayList<String>();
        try {
            process = Runtime.getRuntime().exec("ps -aux");
            BufferedReader input = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line = "";
            while ((line = input.readLine()) != null) {
                processList.add(line);
            }
            input.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        for (String line : processList) {
            System.out.println(line);
        }
    }
}

调用shell脚本,判断是否正常执行,如果正常结束,Process的waitFor()方法返回0

    public static void callShell(String shellString) {
        try {
            Process process = Runtime.getRuntime().exec(shellString);
            int exitValue = process.waitFor();
            if (0 != exitValue) {
                log.error("call shell failed. error code is :" + exitValue);
            }
        } catch (Throwable e) {
            log.error("call shell failed. " + e);
        }
    }

实现方式二、使用Apache Commons Exec 工具类

参考:https://stackoverflow.com/questions/808276/how-to-add-a-timeout-value-when-using-javas-runtime-exec

给出了一个例子可以支持设置命令执行超时时间,可以满足简单使用的要求(先用这个)

String line = "your command line";
CommandLine cmdLine = CommandLine.parse(line);
DefaultExecutor executor = new DefaultExecutor();
ExecuteWatchdog watchdog = new ExecuteWatchdog(60000);
executor.setWatchdog(watchdog);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream);
executor.setStreamHandler(streamHandler);
int exitValue = executor.execute(cmdLine);
System.out.println(exitValue);
System.out.println(outputStream.toString());

参考http://brandnewuser.iteye.com/blog/2181921

稍微复杂一点的例子,可以记录标准输出和错误以及报错时的状态和执行的事件

 

方案二,通过java模拟ssh客户端,登录目标主机后自动执行命令

有点是不占用程序内存,缺点是需要登录可能需要密码

实现方式 使用 http://www.jcraft.com/jsch/  提供的jsch 模拟ssh客户端类,功能强大,支持ssh命令scp sftp 端口转发等各种功能,官网提供完整例子程序,很多开源软件都用这个。

参考:

http://blog.csdn.net/liuxiangke0210/article/details/69257276

http://rensanning.iteye.com/blog/2109675

http://blog.csdn.net/jmyue/article/details/14003783

 

 

 

© 2018, 新之助meow. 原创文章转载请注明: 转载自http://www.xinmeow.com

0.00 avg. rating (0% score) - 0 votes
点赞