How to execute cmd line of psexec and log to text file in a single line using JAVA?

给你一囗甜甜゛ 提交于 2020-01-24 09:31:08

问题


I am trying to execute the following line in java(with escaped characters):

"psexec -i -d \\\\computerName -u user -p pass calc 2>  
 somePath\\psexecOut.txt"    

I use the following method to execute cmd lines:

private static String executeCommand(String command) {

    StringBuffer output = new StringBuffer();
    System.out.println("command is = \n"+command);
    Process p;
    try {
        p = Runtime.getRuntime().exec(command);
        p.waitFor();
        BufferedReader reader =
                           new BufferedReader(new InputStreamReader(p.getInputStream()));

                       String line = "";
        while ((line = reader.readLine())!= null) {
            output.append(line + "\n");
        }

    } catch (Exception e) {
        e.printStackTrace();
    }

    return output.toString();

}  

The line is executed and calc is starting , but the log part doesn't work. The log file psexecOut.txt is not created.

When I run the command normally (without excaped characters) in cmd it runs fine and the log file is created, but using java it doesn't create the log file.

I suspect that > needs to be escaped but as I read it's already escaped as it is.

How can I execute the psexec with log to text file in a single cmd line using java like I can do manually in windows console ?


回答1:


Solved:
As lit suggested in the comments: cmd.exe /c works.

So the corrected method is:

private static String executeCommand(String command) {

    StringBuffer output = new StringBuffer();
    System.out.println("command is = \n"+command);
    Process p;
    try {
        p = Runtime.getRuntime().exec("cmd.exe /c "+command); // <-correction done here
        p.waitFor();
        BufferedReader reader =
                           new BufferedReader(new InputStreamReader(p.getInputStream()));

                       String line = "";
        while ((line = reader.readLine())!= null) {
            output.append(line + "\n");
        }

    } catch (Exception e) {
        e.printStackTrace();
    }

    return output.toString();

} 



回答2:


Try putting cmd.exe /C at the beginning of the command? It is cmd.exe that interprets the > redirection.

"cmd.exe /C psexec -i -d \\\\computerName -u user -p pass calc 2> somePath\\psexecOut.txt"   


来源:https://stackoverflow.com/questions/46360801/how-to-execute-cmd-line-of-psexec-and-log-to-text-file-in-a-single-line-using-ja

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!