我想用 grep 跟踪日志文件并通过邮件发送,例如:
tail -f /var/log/foo.log | grep error | mail -s subject name@example.com
我怎样才能做到这一点?
您想在发生电子邮件错误时发送电子邮件?那可能会失败;)
但是,您可以尝试这样的事情:
tail -f $log |
grep --line-buffered error |
while read line
do
echo "$line" | mail -s subject "$email"
done
grep 输出中的每一行都会发送一封电子邮件。
运行上面的shell脚本
nohup ./monitor.sh &
所以它将继续在后台运行。
我会试一试。如果仔细检查我讨厌的 bash 代码,也许我会学到一些东西。有可能已经有无数的解决方案可以做到这一点,但我不会去发现,因为我相信你已经拖网过网络海洋的深度和宽度。听起来你想要的可以分为两个位:1)定期获取文件的“最新尾部”,2)如果最新的尾部确实存在,通过电子邮件发送。对于 1) 中的定期间隔,请使用 cron。为了获得 2) 中的最新尾部,您必须跟踪文件大小。下面的 bash 脚本就是这样做的——它是 2) 的解决方案,可以由 cron 调用。它使用缓存的文件大小来计算它需要邮寄的文件块。请注意,对于文件 myfile 会创建另一个文件 .offset.myfile。还,该脚本不允许文件名中包含路径组件。重写或在调用中修复它[例如(cd /foo/bar && segtail.sh zut),假设它被称为 segtail.sh ]。
#!/usr/local/bin/bash
file=$1
size=0
offset=0
if [[ $file =~ / ]]; then
echo "$0 does not accept path components in the file name" 2>&1
exit 1
fi
if [[ -e .offset.$file ]]; then
offset=$(<".offset.$file")
fi
if [[ -e $file ]]; then
size=$(stat -c "%s" "$file") # this assumes GNU stat, possibly present as gstat. CHECK!
# (gstat can also be Ganglias Status tool - careful).
fi
if (( $size < $offset )); then # file might have been reduced in size
echo "reset offset to zero" 2>&1
offset=0
fi
echo $size > ".offset.$file"
if [[ -e $file && $size -gt $offset ]]; then
tail -c +$(($offset+1)) "$file" | head -c $(($size - $offset)) | mail -s "tail $file" foo@bar
fi
怎么样:
邮件 -s “catalina.out 错误” blah@myaddress.com < grep ERROR catalina.out