背景
写了个postman脚本,准备放在服务器每隔5分钟执行一次,postman命令在/usr/local/bin/postman目录
现象
cron脚本
- crontab系统配置
[root@node2 ~]# cat /etc/crontab
SHELL=/bin/bash
PATH=/sbin:/bin:/usr/sbin:/usr/bin
MAILTO=root
HOME=/
2.crontab定时任务
*/5 * * * * /mnt/script/postman/b.sh
- /mnt/script/postman/b.sh
#!/bin/sh
postman collection run /mnt/script/postman/blade-1.json >> /tmp/cron_test.log
执行结果
/tmp/cron_test.log中没有执行记录,脚本中的接口也没触发
分析过程
检查cront服务是否正常运行
service crond status
Redirecting to /bin/systemctl status crond.service
● crond.service - Command Scheduler
Loaded: loaded (/usr/lib/systemd/system/crond.service; enabled; vendor preset: enabled)
Active: active (running) since Sun 2023-06-25 17:01:35 CST; 44min ago
Main PID: 75796 (crond)
Tasks: 1
Memory: 664.0K
CGroup: /system.slice/crond.service
└─75796 /usr/sbin/crond -n
Jun 25 17:25:01 node2 crond[75796]: sendmail: fatal: parameter inet_interfaces: no local interface found for ::1
服务正常
检查定时任务是否正常触发
查看定时任务日志tail -100f /var/log/cron
Jun 25 17:49:01 node2 CROND[90291]: (root) CMD (/mnt/script/postman/b.sh)
可以看到任务已经被触发了
检查触发的任务是否正常运行
添加定时任务
* * * * * date >> /tmp/cron_test.log
在/tmp/cron_test.log中有出现执行结果,说明定时任务可以正常触发和执行
Sun Jun 25 17:52:01 CST 2023
检查定时任务环境
因为postman是单独安装的,cli在/usr/local/bin目录下,想看一下cron执行的时候环境变量是什么
修改/mnt/script/postman/b.sh
echo $PATH >> /tmp/cron_test.log
postman collection run /mnt/script/postman/blade-1.json >> /tmp/cron_test.log
cron执行后发现/tmp/cron_test.log中的PATH不对。。。。
Sun Jun 25 17:34:01 CST 2023
/usr/bin:/bin
至此问题原因找到了,是因为cron执行环境中没有postman命令,只要触发一下环境配置或者指定postman的路径即可
修改方案
方案一 :添加环境变量
修改/mnt/script/postman/b.sh脚本
#!/bin/sh
. /etc/profile #环境变量生效 前提是你的命令所在环境有在这个文件中配置
echo $PATH >> /tmp/cron_test.log
postman collection run /mnt/script/postman/blade-1.json >> /tmp/cron_test.log
方案二:直接指定命令目录
修改/mnt/script/postman/b.sh脚本
#!/bin/sh
/usr/local/bin/postman collection run /mnt/dengwei/postman/blade-1.json >> /tmp/cron_test.log