ExecShellResult不喜欢我的烟斗

时间:2017-10-23 18:41:08

标签: linux awk grep cut cfengine

我在cfengine v2.2.1a中写了以下ExecShellResult片段:

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 ...]

请注意,当我们在echo下运行shellcommands:命令时,会显示错误。到那时,${time_drift}变量已经过评估,其结果显示我们错误地调用了cut的{​​{1}}选项,抱怨我们没有将任何内容传递给-d这显然不是真的。

这令人困惑,因为-d使用相同的语法并且工作正常。

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

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

1 个答案:

答案 0 :(得分:0)

我不确定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
相关问题