繁体   English   中英

如何在java程序中调用shellscript?

[英]How to call shellscript in java program?

如何在java程序中调用shellscript?

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

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

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

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

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);
}
 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);
        }
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM