跳转至

crontab环境变量

crontab环境变量.

1、大致功能就是找出未在fstab中挂载的磁盘,并发送到云平台告警。

#!/bin/bash
source /etc/profile

remote_address="http://1.1.1.1:6666"
user=xxxx
pass=xxxx

except_block=("/dev/sr0" "/dev/cdrom" "/dev/dvd")

blkid_output=$(blkid -s UUID)
all_block=()


check_useless() {
  target=$1
  found=0
  for item in "${except_block[@]}"; do
      if [ "$item" == "$target" ]; then
          found=1
          break
      fi
  done
  echo $found
}

check_block_in_fstab(){
  uuid=$1
  device=$2
  uuid_wc=`grep $uuid /etc/fstab |wc -l`
  device_wc=`grep $device /etc/fstab|wc -l`
  appear_counts=$(($uuid_wc + $device_wc))
  echo $appear_counts

}

main(){
   while IFS= read -r line; do
     uuid=$(echo "$line" | awk '{print $2}' | cut -d "=" -f2 | sed 's/"//g')
     device=$(echo "$line" | awk '{print $1}' | sed 's/://g')

     found=`check_useless $device`
     if [ $found -eq 0 ];then
        check_res=`check_block_in_fstab $uuid $device`
        if [ $check_res -ne 1 ];then
            JWT_TOKEN=`curl -s -X POST -d "email=${user}&password=${pass}" "${remote_address}/jwt/api-token-path/"|awk -F '[:"]' '{print $8}'`

            curl "${remote_address}/receive/ReceiveCustomAlarm/" \
               -X POST \
               -H "Content-Type: application/json" \
               -H "Authorization: Bearer $JWT_TOKEN" \
               -d "{
                     \"subject\": \"有磁盘未在fstab中\",
                     \"ip\": \"`hostname -I | cut -d' ' -f1`\",
                     \"hostname\": \"`hostname`\",
                     \"source\": \"服务器\",
                     \"alarm_template_id\": 1, 
                     \"alarm_content\": {
                       \"title\": \"有磁盘未在fstab中\",
                       \"msg\": \"${uuid}-${device}\"
                     }
                   }" 
        fi
     fi
   done <<< "$blkid_output"
}

2、本身这个东西没啥有趣的,但是发现环境变量不一样,每次都能在环境变量上出问题,但是每次解决的方式也不一样,我就记录一下这次的处理方式,供小伙伴的解忧。

2.1、因为脚本用到了blkid这个命令

blkid: /usr/sbin/blkid /usr/share/man/man8/blkid.8.gz

2.2、我看crontab文件的内容,以为不会有什么问题,毕竟手动执行没有问题

cat /etc/crontab 
SHELL=/bin/bash
PATH=/sbin:/bin:/usr/sbin:/usr/bin
MAILTO=root

# For details see man 4 crontabs

# Example of job definition:
# .---------------- minute (0 - 59)
# |  .------------- hour (0 - 23)
# |  |  .---------- day of month (1 - 31)
# |  |  |  .------- month (1 - 12) OR jan,feb,mar,apr ...
# |  |  |  |  .---- day of week (0 - 6) (Sunday=0 or 7) OR sun,mon,tue,wed,thu,fri,sat
# |  |  |  |  |
# *  *  *  *  * user-name  command to be executed

2.3、然后放到crontab之后,发现命令没有执行,在crontab中的环境变量是

/usr/bin:/bin

2.4、所以需要的命令不在环境变量中,解决方式

2.4.1、使用全路径

2.4.2、引入/etc/profile,加载/etc/profile 文件中的环境变量



觉得有用的老铁们可以"微信"赞助一杯82年的雪碧呦。
txtddd
本文阅读量  次

评论