如何使用JAVA在一行中执行psexec的cmd行并记录到文本文件?
我正在尝试用java执行以下行(使用转义字符): 我使用以下方法执行cmd行:如何使用JAVA在一行中执行psexec的cmd行并记录到文本文件?,java,cmd,Java,Cmd,我正在尝试用java执行以下行(使用转义字符): 我使用以下方法执行cmd行: private static String executeCommand(String command) { StringBuffer output = new StringBuffer(); System.out.println("command is = \n"+command); Process p; try { p = Runtime.getRuntime()
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();
}
执行该行并开始计算,但日志部分不起作用。未创建日志文件psexecOut.txt
当我在cmd中正常运行命令时(不带替换字符),它运行良好,并且创建了日志文件,但是使用java它不会创建日志文件
我怀疑
需要转义,但据我所知,它已经按原样转义了
如何像在windows控制台中手动执行一样,使用java在单个cmd行中执行带有log to text文件的psexec?已解决:正如评论中所建议的:
cmd.exe/c
有效
因此,正确的方法是:
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();
}
private静态字符串执行命令(String命令){
StringBuffer输出=新的StringBuffer();
System.out.println(“命令为=\n”+命令);
过程p;
试一试{
p=Runtime.getRuntime().exec(“cmd.exe/c”+命令);//尝试将cmd.exe/c放在命令开头?解释>重定向的是cmd.exe
"cmd.exe /C psexec -i -d \\\\computerName -u user -p pass calc 2> somePath\\psexecOut.txt"
你试过把cmd.exe/C
放在命令的开头吗?是cmd.exe解释了
重定向。哇,谢谢你,老兄。这就成功了!你太棒了
"cmd.exe /C psexec -i -d \\\\computerName -u user -p pass calc 2> somePath\\psexecOut.txt"