7个自定义定时任务并发送消息至邮箱或企业微信案例(crontab和at)

2022-11-07,,,,

前言

    更好熟悉掌握at、crontab定时自定义任务用法。
    实验at、crontab定时自定义任务运用场景案例
    作业、笔记需要。

定时计划任务相关命令及配置文件简要说明

at 工具

由包 at 提供

依赖与atd服务,需要启动才能实现at任务

at队列存放在/var/spool/at目录中,ubuntu存放在/var/spool/cron/atjobs目录下

执行任务时PATH变量的值和当前定义任务的用户身份一致

at格式

at [option] TIME

常见参数:

-m :当指定的任务被完成之后,将给用户发送邮件,即使没有标准输出
-I :atq的别名
-d :atrm的别名
-v :显示任务将被执行的时间
-c :打印任务的内容到标准输出
-V :显示版本信息
-q :后面加<列队> 使用指定的列队
-f :后面加<文件> 从指定文件读入任务而不是从标准输入读入
-t :后面<时间参数> 以时间参数的形式提交要运行的任务

周期性任务计划cron相关的程序包:

cronie:主程序包,提供crond守护进程及相关辅助工具

crontabs:包含CentOS提供系统维护任务

cronie-anacron:cronie的补充程序,用于监控cronie任务执行状况,如:cronie中的任务在过去该运行的时间点未能正常运行,则anacron会随后启动一次此任务cron

依赖于crond服务,确保crond守护处于运行状态:

#CentOS 7 以后版本:
systemctl status crond
#CentOS 6:
service crond status

crontab命令格式

crontab [-u user] [-l | -r | -e] [-i]

crontab常用命令

-l 列出所有任务
-e 编辑任务
-r 移除所有任务
-i 同-r一同使用,以交互式模式移除指定任务
-u user 指定用户管理cron任务,仅root可运行

配置文件:/etc/crontab

[root@localhost ~]# vim /etc/crontab
SHELL=/bin/bash #默认的SHELL类型
PATH=/sbin:/bin:/usr/sbin:/usr/bin #默认的PATH变量值,可修改为其它路径
MAILTO=root #默认标准输出和错误发邮件给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

m h dom mon dow command

user-name command to be executed


| | | | | |

| | | | | --- 预执行的命令

| | | | ----- 表示星期0~7(其中星期天可以用0或7表示)

| | | ------- 表示月份1~12

| | --------- 表示日期1~31

| ----------- 表示小时1~23(0表示0点)

------------- 表示分钟1~59 每分钟用*或者 */1表示


- 计划任务时间表示法: ```sh
(1) 特定值
给定时间点有效取值范围内的值
(2) *
给定时间点上有效取值范围内的所有值,表示“每...”,放在星期的位置表示不确定
(3) 离散取值
#,#,#
(4) 连续取值
#-#
(5) 在指定时间范围上,定义步长
/#: #即为步长
(6) 特定关健字
@yearly 0 0 1 1 *
@annually 0 0 1 1 *
@monthly 0 0 1 * *
@weekly 0 0 * * 0
@daily 0 0 * * *
@hourly 0 * * * *
@reboot Run once after reboot

自定义任务案例

    案例:一次性在今天16:20分,自动在/data/目录下创建文件

    [16:10:57 root@localhost ~]#at 16:20
    warning: commands will be executed using /bin/sh
    at> touch /data/file1.txt
    at> <EOT>
    job 12 at Tue Aug 23 16:20:00 2022 [16:12:36 root@localhost ~]#at 16:20 2022-08-23
    warning: commands will be executed using /bin/sh
    at> touch /data/file02.txt
    at> <EOT>
    job 13 at Tue Aug 23 16:20:00 2022 [16:13:39 root@localhost ~]#at now + 6 min
    warning: commands will be executed using /bin/sh
    at> touch /data/file03.txt
    at> <EOT>
    job 14 at Tue Aug 23 16:20:00 2022 [16:17:18 root@localhost ~]#at 04pm + 20 min
    warning: commands will be executed using /bin/sh
    at> touch /data/file4.txt
    at> <EOT>
    job 16 at Tue Aug 23 16:20:00 2022

    明天凌晨 01:06重启httpd服务,并发送邮件通知是否成功

    [01:04:56 root@rocky8_31 ~]#at 01:06
    warning: commands will be executed using /bin/sh
    at> systemctl restart httpd &>/dev/null ;if [ $? -eq 0 ] ;then { echo $(hostname -I) http服务重启成功|mailx -s "重启服务通知" 1024320609@qq.com ; } ;else { echo $(hostname -I)http服务重启成功|mailx -s "重启服务警告" 1024320609@qq.com ;} ;fi
    at> <EOT>
    job 5 at Tue Aug 30 01:06:00 2022

    每周二凌晨打包/etc/下所有文件到/data/目录下后

    [02:16:37 root@rocky8_31 ~]#crontab -l
    PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/root/bin
    1 * * * * echo %IP_$PATH >> /root/text.txt
    17 2 * * 2 tar -cf /data/etc/etc_$(date +"\%F_\%T").tar.gz /etc/* &> /dev/null & if [ $? -eq 0 ] ;then { echo $(hostname -I):etc目录打包备份成功|mailx -s "数据备份通知" 1024320609@qq.com ; } ;else { echo $(hostname -I):etc目录打包备份失败|mailx -s "数据备份警告" 1024320609@qq.com ;} ;fi

    每分钟自动检查内存超过百分之80%,将自动邮箱报警

    [16:08:45 root@rocky8_31 ~]#vim memcheck.sh
    
      1 #!/bin/bash
    2 # **********************************************************
    3 #
    4 # * Author : 张雪龙
    5 # * Email : 1024320609@qq.com
    6 # * Create time : 2022-08-30 16:05
    7 # * Filename : memcheck.sh
    8 # * Description :
    9 #
    10 # **********************************************************
    11
    12
    13
    14 str=$(free|awk '/^Mem/{if($3/$2>0.65)printf("当前内存:%.2fG,内存占比:%.2f%\n", $3/1024/1024,$3/$2*100)}')
    15 [ $str ]&&{ echo $str|mailx -s "$(hostname -I |awk 'NR==1{print $1}'):内存警告通知" 1024320609@qq.com ;} [16:09:49 root@rocky8_31 ~]#vim /etc/crontab 1 SHELL=/bin/bash
    2 PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/root/bin
    3 MAILTO=root
    4
    5 # For details see man 4 crontabs
    6
    7 # Example of job definition:
    8 # .---------------- minute (0 - 59)
    9 # | .------------- hour (0 - 23)
    10 # | | .---------- day of month (1 - 31)
    11 # | | | .------- month (1 - 12) OR jan,feb,mar,apr ...
    12 # | | | | .---- day of week (0 - 6) (Sunday=0 or 7) OR sun,mon,tue,wed,thu,fri,sat
    13 # | | | | |
    14 # * * * * * user-name command to be executed
    15
    16 */1 * * * * root bash /root/memcheck.sh

    每十分钟自动检查硬盘分区超过百分之80%,将自动邮箱报警

    #1、执行的脚本
    [16:47:26 root@rocky8_31 ~]#vim check_disk.sh 1 #!/bin/bash
    2 # **********************************************************
    3 #
    4 # * Author : 张雪龙
    5 # * Email : 1024320609@qq.com
    6 # * Create time : 2022-08-30 16:47
    7 # * Filename : check_disk.sh
    8 # * Description :
    9 #
    10 # **********************************************************
    11
    12
    13 str=$(df -h|awk -F" +|%" '/^\/dev\/(nvm|sdb)/{print $5}'|sort -rn|head -n 1)&&[ $str -gt 24 ]&&{ echo 磁盘分区空间使用率 $str% |mailx -s "$(hostname -I |awk 'NR==1{print $1}'):磁盘警告通知" 1024320609@qq.com ;} #2、编辑自定义任务
    [16:50:25 root@rocky8_31 ~]#vim /etc/crontab
    1 SHELL=/bin/bash
    2 PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/root/bin
    3 MAILTO=root
    4
    5 # For details see man 4 crontabs
    6
    7 # Example of job definition:
    8 # .---------------- minute (0 - 59)
    9 # | .------------- hour (0 - 23)
    10 # | | .---------- day of month (1 - 31)
    11 # | | | .------- month (1 - 12) OR jan,feb,mar,apr ...
    12 # | | | | .---- day of week (0 - 6) (Sunday=0 or 7) OR sun,mon,tue,wed,thu,fri,sat
    13 # | | | | |
    14 # * * * * * user-name command to be executed
    15
    16 #0 */1 * * * root bash /root/memcheck.sh
    17 */1 * * * * root bash /root/check_disk.sh #3、运行结果

    每日统计网站IP访问量(以Apache访问日志为例),将自动发送邮箱

    #1、日志文件格式
    [18:24:12 root@rocky8_31 ~]#tail /var/log/httpd/access_log-20220828
    192.168.100.1 - - [27/Aug/2022:05:34:49 +0800] "GET / HTTP/1.1" 200 18 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.69 Safari/537.36"
    192.168.100.31 - - [27/Aug/2022:14:52:40 +0800] "GET / HTTP/1.1" 200 18 "-" "curl/7.61.1"
    192.168.100.31 - - [27/Aug/2022:14:52:41 +0800] "GET / HTTP/1.1" 200 18 "-" "curl/7.61.1"

192.168.100.31 - - [27/Aug/2022:14:52:42 +0800] "GET / HTTP/1.1" 200 18 "-" "curl/7.61.1"

192.168.100.31 - - [27/Aug/2022:14:52:42 +0800] "GET / HTTP/1.1" 200 18 "-" "curl/7.61.1"

192.168.100.31 - - [27/Aug/2022:14:52:43 +0800] "GET / HTTP/1.1" 200 18 "-" "curl/7.61.1"

192.168.100.31 - - [27/Aug/2022:14:52:43 +0800] "GET / HTTP/1.1" 200 18 "-" "curl/7.61.1"

192.168.100.31 - - [27/Aug/2022:14:52:44 +0800] "GET / HTTP/1.1" 200 18 "-" "curl/7.61.1"

192.168.100.31 - - [27/Aug/2022:14:52:45 +0800] "GET / HTTP/1.1" 200 18 "-" "curl/7.61.1"

192.168.100.31 - - [27/Aug/2022:14:52:48 +0800] "GET / HTTP/1.1" 200 18 "-" "curl/7.61.1"

2、编辑定时任务

[18:24:58 root@rocky8_31 ~]#crontab -l

PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/root/bin

25 18 * */1 * echo -e " 访问量 IP地址\n $(cat /var/log/httpd/access_log-20220828|awk '{print $1}'|sort |uniq -c|sort -nr|head -n 3)"| mailx -s "$(hostname -I |awk 'NR==1{print $1}'):网站访问IP统计" 1024320609@qq.com

运行显示结果


![image-20220830182649078](https://img2022.cnblogs.com/blog/1301995/202208/1301995-20220830235634825-1458225311.png) 7. 统计192.168.100.0网络正在使用的IP地址,并发送到企业微信群中。 ```sh
#企业微信上传脚本
[23:24:20 root@rocky8_31 ~]#vim weixin2.sh 1 #!/bin/bash
2 # **********************************************************
3 #
4 # * Author : 张雪龙
5 # * Email : 1024320609@qq.com
6 # * Create time : 2022-08-30 22:20
7 # * Filename : weixin2.sh
8 # * Description :
9 #
10 # **********************************************************
11
12 #!/bin/bash
13 content=${@:1}
14 content=${content//\ /}
15 content=${content//\"/}
16 date=$(date +%Y-%m-%d)
17 time=$(date "+%H:%M:%S")
18 content="
19 **WGCLOUD**
20 >告警时间:$date.$time
21 >告警详情:$content
22
23
24 "
25 webHookUrl="https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=9d3676eg-4f6e-7fgf-2325-06976f5qt580"
26 content='{"msgtype": "markdown","markdown": {"content": "'$content'","mentioned_list":"@all"},}'
27 echo "content : $content"
28 curl --data-ascii "$content" $webHookUrl
29 echo "over!" #异步ping脚本,并执行weixin2.sh上传通知消息
[23:34:19 root@rocky8_31 ~]#vim check_ip.sh 1 #!/bin/bash
2 # **********************************************************
3 #
4 # * Author : 张雪龙
5 # * Email : 1024320609@qq.com
6 # * Create time : 2022-08-30 23:12
7 # * Filename : check_ip.sh
8 # * Description :
9 #
10 # **********************************************************
11
12 NET=192.168.100
13 > /root/hosts.txt
14 for i in {1..254};do
15 {
16 if ping -c1 -W1 $NET.$i &> /dev/null ;then
17 echo $NET.$i, | tee -a /root/hosts.txt
18 fi
19 }&
20 done
21
22 bash /root/weixin2.sh "$(cat /root/hosts.txt) \n网络通常" #2、编辑定时任务
[23:47:20 root@rocky8_31 ~]#crontab -l
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/root/bin
50 23 * */1 * bash /root/check_ip.sh #消息到企业微信结果显示

7个自定义定时任务并发送消息至邮箱或企业微信案例(crontab和at)的相关教程结束。

《7个自定义定时任务并发送消息至邮箱或企业微信案例(crontab和at).doc》

下载本文的Word格式文档,以方便收藏与打印。