我有以下脚本使用Java java.lang.ProcessBuilder
执行shell命令,如果我不使用参数,该命令可以正常工作:
<cfif IsDefined("FORM.cmd")>
<cfif Server.OS.Name CONTAINS "Mac" or Server.OS.Name CONTAINS "Linux" or Server.OS.Name IS "UNIX">
<cfset cmd = "sh -c #FORM.cmd#">
<cfelseif Server.OS.Name CONTAINS "Windows">
<cfset cmd = "cmd.exe /c #FORM.cmd#">
<cfelse>
<cfset cmd = "sh -c #FORM.cmd#">
</cfif>
<cfscript>
str = htmleditformat(REReplace(cmd,"""","'","ALL"));
exec = str.split(" ");
pb = createObject("java","java.lang.ProcessBuilder").init(exec);
pb.redirectErrorStream(true);
proc = pb.start();
proc.waitFor();
isr = createObject("java","java.io.InputStreamReader").init(proc.getInputStream());
br = createObject("java","java.io.BufferedReader").init(isr);
line = br.readLine();
while (isDefined("line")) {
writeoutput(line & '<br>');
line = br.readLine();
}
br.close();
isr.close();
</cfscript>
</cfif>
如果我的#FORM.cmd#
是uname
,则输出符合我的预期:
Linux
但如果我的#FORM.cmd#
为uname -a
,则脚本仅在uname
参数之外执行-a
。所以我想我会使用java数组来添加参数:
<cfscript>
args = createObject("java", "java.util.ArrayList").init();
args.add("sh");
args.add("-c");
args.add("uname");
args.add("-a");
pb = createObject("java","java.lang.ProcessBuilder").init(args);
pb.redirectErrorStream(true);
proc = pb.start();
proc.waitFor();
isr = createObject("java","java.io.InputStreamReader").init(proc.getInputStream());
br = createObject("java","java.io.BufferedReader").init(isr);
line = br.readLine();
while (isDefined("line")) {
writeoutput(line & '<br>');
line = br.readLine();
}
br.close();
isr.close();
</cfscript>
同样的问题。我做错了什么?
答案 0 :(得分:0)
&#34; -a&#34;作为sh的论据传入,而不是uname。你需要把&#34; uname -a&#34;在同一个arg中,即:
args.add("sh");
args.add("-c");
args.add("uname -a");
如果有助于澄清,要直接从命令行执行此操作,您需要输入:
sh -c "uname -a"