我在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
的-d
选项,抱怨我们没有传递任何东西给-d
,这显然不是真的。这是令人困惑的,因为
${active_interface_mac}
使用相同的语法并且工作得很好。我试着用
| tail -1 | sed 's///'
替换第二个grep,另一个grep -o [0-9]*.[0-9]
或者我能想到的任何东西,包括/usr/bin/cut -f1 -d'${spc}'
。我显然不能使用awk
,因为cfengine将$(NF)
解释为ExecShellResult
的一部分的括号,即使是转义的。要从
ntpdate
的输出中提取实际秒数,还需要哪些选项? 最佳答案
我不确定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