我通过java执行了ldapsearch命令。请参阅以下代码。
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class TestMain
{
public static void main(String[] args) throws InterruptedException, IOException
{
String ldspCmd ="ldapsearch -ZZ -h ldap-url.com -x -D cn=username,ou=webapps,ou=ec,o=uoa -w $(echo PassWord | base64 -di) -b ou=ec_users,dc=ec,dc=auckland,dc=ac,dc=nz \"(groupMembership=cn=bpmusers,ou=ec_group,dc=ec,dc=auckland,dc=ac,dc=nz)\"";
String output = executeCommand(ldspCmd);
System.out.println(output);
}
private static String executeCommand(String command) {
StringBuffer output = new StringBuffer();
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");
}
BufferedReader errorReader =
new BufferedReader(new InputStreamReader(p.getErrorStream()));
String erroLine = "";
while ((erroLine = errorReader.readLine())!= null) {
output.append(erroLine + "\n");
}
} catch (Exception e) {
e.printStackTrace();
}
return output.toString();
}
}
但我收到错误" ldapsearch:无法解析调试值" i)""。
但是当我通过命令行执行相同的命令时,它会正确执行并返回记录。
我在这里做错了什么?任何人都可以帮我解决这个问题吗?
答案 0 :(得分:2)
您的参数列表中的$(echo PassWord | base64 -di)
之类的结构由shell解释和处理。当您使用Runtime.exec
从Java调用命令时,不是使用shell,您将命令直接传递给操作系统,因此您无法获得shell解释这些结构。
如果您需要这些好处,则需要显式调用shell。 此外,Java没有相同的复杂逻辑来将参数拆分为shell所执行的命令。 Java只是在空格字符处剪切参数列表。
因此,在您的executeCommand
方法中,您有一行:
p = Runtime.getRuntime().exec(command);
您应该将其更改为:
// Add shell invocation around the above command
String[] shellCommand = { "/bin/bash", "-c", command };
p = Runtime.getRuntime().exec(shellCommand);