批量添加定时任务
脚本如下
#!/bin/bash
# 检查参数数量
if [ "$#" -lt 2 ]; then
echo "Usage: $0 <hosts_file> <cron_job_file>"
echo "cron_job_file format: <cron_schedule> <command>"
exit 1
fi
hosts_file="$1"
cron_job_file="$2"
# 检查文件是否存在
if [ ! -f "$hosts_file" ]; then
echo "Error: Hosts file does not exist."
exit 1
fi
if [ ! -f "$cron_job_file" ]; then
echo "Error: Cron job file does not exist."
exit 1
fi
# 读取主机文件并添加定时任务
while IFS= read -r host
do
echo "Adding cron jobs to $host..."
# 读取cron任务并通过heredoc传递给远程主机
ssh "$host" bash << EOF
# 创建临时文件
temp_file=\$(mktemp)
# 导出当前的 crontab 内容到临时文件
crontab -l > "\$temp_file" 2>/dev/null
# 读取并添加新的定时任务
while IFS= read -r job; do
if grep -Fq "\$job" "\$temp_file"; then
echo "The cron job '\$job' already exists on $host. Skipping."
else
echo "\$job" >> "\$temp_file"
echo "Added new cron job: \$job"
fi
done << 'CRON_JOBS'
$(cat "$cron_job_file")
CRON_JOBS
# 更新 crontab
crontab "\$temp_file"
# 删除临时文件
rm "\$temp_file"
echo "Cron jobs updated successfully on $host."
EOF
if [ $? -eq 0 ]; then
echo "Successfully added cron jobs to $host"
else
echo "Failed to add cron jobs to $host"
fi
echo "-----------------------------------"
done < "$hosts_file"
echo "Batch cron job addition completed."
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
上次更新: 2024/10/18, 18:39:32