【问题标题】:ExecShellResult doesn't like my pipesExecShellResult 不喜欢我的管道
【发布时间】:2018-04-04 09:54:10
【问题描述】:

我在cfengine v2.2.1a 中编写了以下@987654321@ 片段:

control:
    active_interface_mac = ( ExecShellResult(/sbin/ifconfig ${active_interface} | /usr/bin/grep 'ether ' | /usr/bin/cut -f2 -d' ') )
    ...
    time_drift = ( ExecShellResult(/usr/sbin/ntpdate -d pool.ntp.org 2>/dev/null | /usr/bin/grep -o 'offset.*sec' | /usr/bin/cut -f2 -d' ') )
    ...
shellcommands:
    "/bin/echo ${time_drift}" inform=true syslog=true

当从命令行运行上述内容时,它显然可以正常工作:

$ ntpdate ...
0.183693

但是,如果在 cfengine 中运行,我会收到语法错误:

$ cfagent -qIK
Executing script /bin/echo /usr/bin/cut...(timeout=0,uid=-1,gid=-1)
cfengine:/bin/echo /usr/: /usr/bin/cut
cfengine: Finished script /bin/echo /usr/bin/cut
cfengine: 
Executing script /bin/echo  option requires an argument -- d usage...(timeout=0,uid=-1,gid=-1)
cfengine:/bin/echo  opti: option requires an argument -- d usage
cfengine: Finished script /bin/echo  option requires an argument -- d usage
cfengine: 
Executing script /bin/echo  cut -b list [-n] [file ...]        cut -c list [file ...]        cut -f list [-s] [-d delim] [file ...]...(timeout=0,uid=-1,gid=-1)
cfengine:/bin/echo  cut : cut -b list [-n] [file ...] cut -c list [file ...] cut -f list [-s] [-d delim] [file ...]
cfengine: Finished script /bin/echo  cut -b list [-n] [file ...]        cut -c list [file ...]        cut -f list [-s] [-d delim] [file ...]

请注意,当我们在shellcommands: 下运行echo 命令时会显示错误。到那时,${time_drift} 变量已经被求值,它的结果显示我们错误地调用了cut-d 选项,抱怨我们没有向-d 传递任何东西,这显然不是真的。

这令人费解,因为${active_interface_mac} 使用相同的语法并且完美运行。

我尝试将第二个 grep 替换为 | tail -1 | sed 's///'、另一个 grep -o [0-9]*.[0-9] 或我能想到的任何其他内容,包括 /usr/bin/cut -f1 -d'${spc}'。我显然不能使用 awk,因为 cfengine 将 $(NF) 解释为括号,它们是 ExecShellResult 的一部分,即使在转义时也是如此。

我还有哪些其他选项可以从ntpdate 的输出中提取我的实际秒值?

【问题讨论】:

    标签: linux awk grep cut cfengine


    【解决方案1】:

    我不确定 cfengine 2,我看不出在您的示例中会出现什么问题 但对于 cfengine 3:

    bundle agent main
    {
      vars:
    
        "ntpdate_s"
          string => execresult( "/usr/sbin/ntpdate -d pool.ntp.org 2> /dev/null | /usr/bin/awk '/offset .* sec/ {print $10}'", useshell ),
          if => not( isvariable( offset ) );
    
      reports:
        "Mac address of wlan0 $(sys.hardware_mac[wlan0])";
        "Offset is $(ntpdate_s)";
    }
    

    输出:

    R: Mac address of wlan0 5c:e0:c5:9f:f3:8f
    R: Offset is 0.027672
    

    【讨论】:

      猜你喜欢
      • 2020-10-13
      • 1970-01-01
      • 1970-01-01
      • 2019-10-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-26
      • 1970-01-01
      相关资源
      最近更新 更多