从Java Web应用程序调用shell命令

时间:2015-10-29 02:49:34

标签: java web-services shell exec

我正在通过在其中创建Web服务来开发Java Web Application。从我需要调用shell级别命令的服务之一,我正在使用以下命令:

Process p = Runtime.getRuntime().exec(command);

在执行时,我收到以下错误“CreateProcess error = 2”,之后服务器终止。

知道什么是错的,或者是否有其他更好的方法从Tomcat等服务器上托管的Web服务调用shell命令

我在网络服务中使用的标准代码:

        @RequestMapping("/user/testDetails")
        public UserResult testDetails(@RequestParam(value="username") String username) {
            System.out.println("Inside User Details REST");
            User user = userService.getUserByName(username);            
            String s = null;             
            try {                
                Process p = Runtime.getRuntime().exec("dir");                
                BufferedReader stdInput = new BufferedReader(new
                     InputStreamReader(p.getInputStream()));     
                BufferedReader stdError = new BufferedReader(new
                     InputStreamReader(p.getErrorStream()));
                System.out.println("Here is the standard output of the command:\n");
                while ((s = stdInput.readLine()) != null) {
                    System.out.println(s);
                }                
                System.out.println("Here is the standard error of the command (if any):\n");
                while ((s = stdError.readLine()) != null) {
                    System.out.println(s);
                }                
               // System.exit(0);
            }
            catch (IOException e) {
                System.out.println("exception happened - here's what I know: ");
                e.printStackTrace();
                //System.exit(-1);
            }           
            return new UserResult(user, "1", null);
        }

0 个答案:

没有答案