我编写了这个脚本,用于检查某个文件是否已被更改:
#!/bin/bash
path=$1
if [ -z "$path" ]; then
echo "usage: $0 [path (required)]" 1>&2
exit 4
fi
lastmodsecs=`stat --format='%Y' $path`
lastmodsecshum=`date -d @$lastmodsecs`
basedate=$newdate
if [ $lastmodsecs != $basedate ]; then
echo "CRITICAL: $path was last modified on $lastmodsecshum !"
newdate=`stat --format='%Y' $path`
exit 1
else
echo "OK: $path hasn't been modified since $lastmodsecshum \(last supervized change\)"
exit 0
fi
如果IF
语句为真,我想用最后一次更改的unix时间设置$ newdate变量,然后将其投影到位于IF
之上的$ basedate变量,那可能吗?
塞尔:
该脚本现在看起来像这样,结果是如果文件已被更改,则检查的状态保持在CRITICAL:/ etc / passwd上次修改date
并且由于某种原因$ persist文件不是正确更新:
#!/bin/bash
path=$1
if [ -z "$path" ]; then
echo "usage: $0 [path (required)]" 1>&2
exit 4
fi
lastmodsecs=`stat --format='%Y' $path`
lastmodsecshum=`date -d @$lastmodsecs`
persist="/usr/local/share/applications/file"
if [ -z $persist ]
then newdate=`stat --format='%Y' $path`
else read newdate < $persist
fi
basedate=$newdate
if [ $lastmodsecs != $basedate ]; then
echo "CRITICAL: $path was last modified on $lastmodsecshum !"
echo $lastmodsecs > $persist
exit 1
else
echo "OK: $path hasn't been modified since $lastmodsecshum \(supervized change\)"
exit 0
fi
答案 0 :(得分:0)
看起来你的代码应该在一个循环中运行,newdate
最初是上次运行的值。通常,如果循环在脚本中,这可以正常工作:
...
# newdate first initialisation
newdate=`stat --format='%Y' $path`
while true
do lastmodsecs=`stat --format='%Y' $path`
lastmodsecshum=`date -d @$lastmodsecs`
basedate=$newdate
if [ $lastmodsecs != $basedate ]; then
echo "CRITICAL: $path was last modified on $lastmodsecshum !"
newdate=$lastmodsecs
exit 1
else
echo "OK: $path hasn't been modified since $lastmodsecshum \(last supervized change\)"
fi
done
但是当我看到你的exit 0
和exit 1
时,这个脚本也打算将状态返回给调用者。您无法使用环境,因为不允许程序修改其父环境。所以唯一的可能性是让调用者管理newdate,或者持久保存到文件中。这最后很简单,无需在调用者中进行修改:
...
persist=/path/to/private/persist/file
# eventual first time initialization or get newdat from $persist
if [ -z $persist ]
then newdate=`stat --format='%Y' $path`
else read newdate < $persist
fi
...
basedate=$newdate
if [ $lastmodsecs != $basedate ]; then
echo "CRITICAL: $path was last modified on $lastmodsecshum !"
echo $lastmodsecs > $persist
exit 1
else
echo "OK: $path hasn't been modified since $lastmodsecshum \(last supervized change\)"
exit 0
fi
当然,当你谈到Nagios时,测试就属于你了......
答案 1 :(得分:0)
要检查文件日期是否比上次检查的时间更新,请尝试:
#!/bin/bash
lastchecked="/tmp/lastchecked.state"
file="/my/file"
# compare file date against date of last check
[[ "$file" -nt "$lastchecked" ]] && echo "$file has been modified since last check"
# remember time when this check was done
touch "$lastchecked"