加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

从Perl调用系统命令

发布时间:2020-12-16 06:22:11 所属栏目:大数据 来源:网络整理
导读:在旧版本的代码中,我们从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
在旧版本的代码中,我们从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中正确地转义那些正则表达式(行号与带有反引号的正则表达式相匹配).

06002

与此同时,我开始怀疑这种方法并寻找更好的方法.

(2)然后我看到一些Stackoverflow问题(here和here)提出了更好的解决方案.

这是代码:

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输出被发送到屏幕,这使我的输出看起来很丑:

06004

b)我无法弄清楚如何选择传递给open的文件句柄的位置(即路径和文件名),即我不知道$lldap_output在哪里.我可以移动/重命名它,或检查它以找出它的位置(或者它实际上没有保存到磁盘)?

基于(2)的问题,这让我觉得我应该回到方法(1),但我不太确定如何

解决方法

一种方法是使用 IPC::Open3来使您的Perl代码能够处理外部程序的stdout和stderr流.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读