在旧版本的代码中,我们从 Perl 调用执行 LDAP 搜索,如下所示:
# Pass the base DN in via the ldapsearch-specific environment variable
# (rather than as the "-b" paramater) to avoid problems of shell
# interpretation of special characters in the DN.
$ENV{LDAP_BASEDN} = $ldn;
$lcmd = "ldapsearch -x -T -1 -h $gLdapServer" .
<snip>
" > $lworkfile 2>&1";
system($lcmd);
if (($? != 0) || (! -e "$lworkfile"))
{
# Handle the error
}
上面的代码将导致成功的 LDAP 搜索,并且该搜索的输出将在文件$lworkfile
.
不幸的是,我们最近在此服务器上重新配置了 openldap,以便在 /etc/openldap/ldap.conf 和 /etc/ldap.conf 中指定“BASE DC=”。这种变化似乎意味着 ldapsearch 忽略了 LDAP_BASEDN 环境变量,所以我的 ldapsearch 失败了。
我尝试了几种不同的修复方法,但到目前为止都没有成功:
(1) 我尝试回到使用 ldapsearch 的“-b”参数,但转义了 shell 元字符。我开始编写转义代码:
my $ldn_escaped = $ldn;
$ldn_escaped =~ s/\/\\/g;
$ldn_escaped =~ s/`/\`/g;
$ldn_escaped =~ s/$/\$/g;
$ldn_escaped =~ s/"/\"/g;
这引发了一些 Perl 错误,因为我没有在 Perl 中正确地转义这些正则表达式(行号与带有反引号的正则表达式匹配)。
Backticks found where operator expected at /tmp/mycommand line 404, at end of line
与此同时,我开始怀疑这种方法并寻找更好的方法。
(2) 然后我看到了一些 Stackoverflow 问题(此处和此处),它们提出了更好的解决方案。
这是代码:
print("Processing...");
# Pass the arguments to ldapsearch by invoking open() with an array.
# This ensures the shell does NOT interpret shell metacharacters.
my(@cmd_args) = ("-x", "-T", "-1", "-h", "$gLdapPool",
"-b", "$ldn",
<snip>
);
$lcmd = "ldapsearch";
open my $lldap_output, "-|", $lcmd, @cmd_args;
while (my $lline = <$lldap_output>)
{
# I can parse the contents of my file fine
}
$lldap_output->close;
我在方法(2)中遇到的两个问题是:
a) 使用参数数组调用 open 或 system 不会让我传递> $lworkfile 2>&1
给命令,因此我无法停止将 ldapsearch 输出发送到屏幕,这使我的输出看起来很难看:
Processing...ldap_bind: Success (0) additional info: Success
b) 我不知道如何选择传递给文件句柄的位置(即路径和文件名)open
,即我不知道在哪里$lldap_output
。我可以移动/重命名它,或者检查它以找出它在哪里(或者它实际上没有保存到磁盘)?
基于(2)的问题,这让我认为我应该回到方法(1),但我不太确定如何