如何在java程序中调用shellscript?

时间:2014-04-28 09:35:24

标签: java linux

如何在java程序中调用shellscript?

String sCommandString="sh /home/admin/ping.sh";
Process p = Runtime.getRuntime().exec(sCommandString);

3 个答案:

答案 0 :(得分:1)

传递IP in命令。我认为这应该有效:

String sCommandString="sh /home/admin/ping.sh 10.12.12.26<Any IP>";

答案 1 :(得分:1)

运行命令和获取输出的最简单方法:

Process p = Runtime.getRuntime().exec("ls");
p.waitFor();
Scanner s = new Scanner(p.getInputStream());
while (s.hasNextLine()) {
    String l = s.nextLine();
    System.out.println(l);
}

答案 2 :(得分:0)

 Executing test.sh shellscript with passing param1 as parameter.Execute and wait for process to start and it will return int value 0 for successfully start of test.sh shellscript.

 Process process = null;
    try {
        int param1 =10;
        String[] command = {"sh", "-c", 'test.sh' + " " + param1};
        process = Runtime.getRuntime().exec(command);
        logger.debug("Process started for [param1 : " + param1 + "]);

        int i = process.waitFor();
        process.getOutputStream().close();

    } catch (Exception e) {
        logger.error("Error while creating process. Full stack trace is as follows ", e);
    } finally {
        try {
            if (process != null) {
                process.getInputStream().close();
            }
        } catch (Exception ex) {
            logger.error("Error while closing process. Full stack trace is as follows ", ex);
        }
    }