2

我制作了一个自定义 sub 来使用 Open3 在 perl 中运行各种终端命令。

我在使用 snmpwalk 时遇到了一个奇怪的问题,当我在终端中运行该命令时它可以工作,但使用 Open3 则不会。

子是这样的:

sub run_cmd {
    my ( $cmd, @args ) = @_;
    my ( $infh, $outfh, $errfh, $pid, $out, $err );

    use Symbol 'gensym';
    $errfh = gensym();    # open3 does not init stderr, we have to do it.

    output( "run_cmd: $cmd @args\n", 2, 1 ); #for debug
    eval { $pid = open3( $infh, $outfh, $errfh, $cmd, @args ); } or do {
        if ($@) {
            output("Error: open3 error $@\n");
            exit $CODES{CRITICAL}; #exit 2;
        }
    };
    {   # anonym block to limit $/ redefinition
        local $/ = undef;
        $out = <$outfh>;
        $err = <$errfh>;
    }
    return ( $out, $err );
}

我称之为:

 ($res, $err) = run_cmd("snmpwalk", "-c public -v1", "somehostname", "NETAPP-MIB::aggrName");

如果我想运行以下命令:

snmpwalk -c public -v1 somehostname NETAPP-MIB::aggrName

它以 $err 的形式返回:

snmpwalk:未指定安全名称

如果我在终端中运行完全相同的命令,它会返回我的结果:

NETAPP-MIB::aggrName.1 = 字符串:“SAS2”

NETAPP-MIB::aggrName.2 = 字符串:“SATA1”

...

我发现 NET::SNMP 可以解决我的问题,但由于硬化的 linux 操作系统没有安装选项,我无法安装它。

我真的不明白为什么它不起作用。

perl -v:5.8.8

谢谢!

4

1 回答 1

1

The problem is the "-c public v1" argument:

($res, $err) = run_cmd("snmpwalk", "-c public -v1", "somehostname", "NETAPP-MIB::aggrName");

The IPC::Open3 open3() function does a fork then exec. exec bypasses the shell when given a list of arguments. So the list needs to be broken down into individual arguments:

($res, $err) = run_cmd("snmpwalk", "-c", "public", "-v1", "somehostname", "NETAPP-MIB::aggrName")
于 2014-05-07T21:45:17.607 回答