本页内容

  • 先决条件
  • 我们要做什么
  • 创建 shell 脚本以添加 Cronjob
  • 执行 Shell 脚本添加 Cronjob
  • 创建 shell 脚本以删除 Cronjob
  • 执行 Shell 脚本删除 Cronjob
  • 结论

手动操作会导致人为错误。频繁地添加和删除 Cronjob 可能是一项非常耗时的任务。在本文中,我们将创建 Shell 脚本,自动完成在 AWS 上 Ubuntu EC2 实例中添加和删除 Cronjob 的操作。要执行这些操作,你需要访问该 EC2 实例。你所使用的用户需要具有 sudo 权限,以便切换到 root 并执行 Cronjob 的添加和删除。

让我们开始吧。

先决条件

  • 对 Shell 脚本和 Cronjob 有基本了解。
  • AWS 账户(如果没有,请创建一个)。
  • 用户具有 sudo 权限的 EC2 实例(如果你还没有 EC2 实例,或者想学习如何创建,请点击此处了解)

我们要做什么

  • 创建 shell 脚本以添加 Cronjob。
  • 执行 Shell 脚本添加 Cronjob。
  • 创建 shell 脚本以删除 Cronjob。
  • 执行 Shell 脚本删除 Cronjob。

创建 shell 脚本以添加 Cronjob

在你的本地 Linux 系统上创建一个文件,并将以下代码添加到其中。你也可以通过以下链接在我的 Github 仓库中找到该代码。

Github Link: 
https://github.com/shivalkarrahul/DevOps/blob/master/aws/shell-scripts/aws-ec2-add-remove-cron-job/add-cronjob.sh
File: add-cronjob.sh
#!/bin/bash

helpFunction()
{ 
	echo ""
	printf "\033[1;32mUsage: $0 -K <internal.pem> -U <internal-user> -I <internal-ip> -a <cron-to-be-added>"
	echo ""
	echo -e "\t-K \".pem key of the server on which a cron job has to be added\""
	echo -e "\t-U UserName of the server on which a cron job has to be added"
	echo -e "\t-I IP of the server on which a cron job has to be added"
	echo -e "\t-a Name of the cron to be added (in double quotes)"
	echo "Add a new Cron Job"
	echo "e.g."
	echo "./add-cronjob.sh -K /Users/cloudcover/Documents/Rahul/access/rahuls.pem -U ubuntu -I ec2-35-180-234-158.eu-west-3.compute.amazonaws.com -a \"0 5 * * 1  testCronJob\""

	echo -e "\033[0m" #reset color
	exit 1 # Exit script after printing help
}

while getopts "I:K:U:a:" opt
do
	case "$opt" in
		K ) internalServerPemKey="$OPTARG" ;;
		U ) internalServerUser="$OPTARG" ;;	
		I ) internalServerIP="$OPTARG" ;;
		a ) addCron="$OPTARG" ;;
		? ) helpFunction ;; # Print helpFunction in case parameter is non-existent
	esac
done

echo  "******************"
#echo $listCronJobs
# Print helpFunction in case parameters are empty
if [ -z "$internalServerIP" ] || [ -z "$internalServerPemKey" ] || [ -z "$internalServerUser" ] || [ -z "$addCron" ]
then
	printf "\033[1;31m"
	echo "Some or all of the parameters are empty";
	helpFunction
fi

# Begin script in case all parameters are correct
printf "\033[1;33m------------------------------------------------------------------Before ssh"
echo -e "\033[0m" #reset color
echo ".pem key of the server on which a new user has be created		:  	$internalServerPemKey"
echo "UserName of the server on which a new user has be created		: 	$internalServerUser"
echo "IP of the server on which a new user has be created			:	$internalServerIP"
echo "Name of the cron to be added				:	$addCron"


printf "\033[1;31mLogging into: "$internalServerPemKey" "$internalServerUser"@"$internalServerIP"\033[0m\n"

ssh -i "$internalServerPemKey" "$internalServerUser"@"$internalServerIP" << HERE
printf "\033[1;33m------------------------------------------------------------------After ssh"
echo -e "\033[0m" #reset color
#echo "Executing connect_prod_cron_new.sh"
#sh connect_prod_cron_new.sh
#sleep 2
echo "after ssh"
echo "IP Of the Server:" 
hostname -I
echo "Hostname of the Server:"
hostname
echo "Changing user to root"
	sudo su <><> EOF
	echo "User Switched To;"
	whoami
	printf "\033[1;33m------------------------------------------------------------------List of Cron Jobs Before Addition"
	echo -e "\033[0m" #reset color
	crontab -l | cat -n
	if [ -n "$addCron" ]
	then
		echo "Inside addCron"
		crontab -l >crontab.tmp
		printf '%s\n' "$addCron" >>crontab.tmp
		crontab crontab.tmp && rm -f crontab.tmp
	fi
	printf "\033[1;33m------------------------------------------------------------------Updated List of Cron Jobs"
	echo -e "\033[0m" #reset color
	crontab -l | cat -n
	printf "\033[1;31mExiting from         ---> "$internalServerPemKey" "$internalServerUser"@"$internalServerIP"\033[0m\n"
	#echo "Existing user	---> $userName"
EOF
HERE

在创建新的 Cronjob 之前,先检查 EC2 实例上是否有任何现有的 Cronjob

登录到 EC2 实例并检查现有的 Cronjob

ssh -i ~/Downloads/example-test.pem 
[email protected]

列出 Cronjob

crontab -l

执行 Shell 脚本添加 Cronjob

转到你的本地 Linux 机器,使用以下命令在 Ubuntu 18.04 EC2 实例上添加一个 Cronjob。这将创建一个每分钟触发一次并将当前日期写入文件的 Cronjob。你可以根据自己的需求更改该 Cronjob。

./add-cronjob.sh -K ~/Downloads/example-test.pem -U ubuntu -I ec2-15-236-64-128.eu-west-3.compute.amazonaws.com -a "* * * * * /bin/date >> /tmp/cron_output"

使用 Shell 脚本在 AWS Linux EC2 实例增删定时任务

现在,你也可以转到 EC2 实例,检查 Cronjob 是否已添加。

ssh -i ~/Downloads/example-test.pem 
[email protected]
sudo -i
crontab -l
cat /tmp/cron_output

在下面的截图中,你可以看到 Cronjob 已添加并每分钟执行一次。

使用 Shell 脚本在 AWS Linux EC2 实例增删定时任务

创建 shell 脚本以删除 Cronjob

现在,如果你认为需要删除已添加的 Cronjob,可以使用我 Github 上提供的 shell 脚本轻松完成。

使用以下代码在你的本地系统上创建一个新文件。

Github Link: 
https://github.com/shivalkarrahul/DevOps/blob/master/aws/shell-scripts/aws-ec2-add-remove-cron-job/remove-cronjob.sh
File: remove-cronjob.sh
#!/bin/bash

helpFunction()
{ 
	echo ""
	printf "\033[1;32mUsage: $0 -K <internal.pem> -U <internal-user> -I <internal-ip> -l <yes/no>"
	echo ""
	echo -e "\t-K \".pem key of the server on which a cron job has to be removed\""
	echo -e "\t-U UserName of the server on which a cron job has to be removed"
	echo -e "\t-I IP of the server on which a cron job has to be removed"
	echo -e "\t-l List the existing Cron Jobs, provide \"yes\" as a parameter. Get a list first and then specify job no which needs to be removed"
	echo -e  "e.g."
	echo "Remove a new Cron Job"
	echo "./remove-cronjob.sh -K /Users/cloudcover/Documents/Rahul/access/rahuls.pem -U ubuntu -I ec2-52-47-90-247.eu-west-3.compute.amazonaws.com -l yes"
	echo -e "\033[0m" #reset color
	exit 1 # Exit script after printing help
}

while getopts "I:K:U:l:" opt
do
	case "$opt" in
	K ) internalServerPemKey="$OPTARG" ;;
	U ) internalServerUser="$OPTARG" ;;	
	I ) internalServerIP="$OPTARG" ;;
	l ) showListOfJobs="$OPTARG" ;;
	? ) helpFunction ;; # Print helpFunction in case parameter is non-existent
	esac
done

echo  "******************"
echo $listCronJobs

# Print helpFunction in case parameters are empty
if [ -z "$internalServerIP" ] || [ -z "$internalServerPemKey" ] || [ -z "$internalServerUser" ] || [ -z "$showListOfJobs" ]
then
	printf "\033[1;31m"

	echo "Some or all of the parameters are empty";
	helpFunction
fi

# Begin script in case all parameters are correct
printf "\033[1;33m------------------------------------------------------------------Before ssh"
echo -e "\033[0m" #reset color
echo ".pem key of the server on which a new user has be created		:  	$internalServerPemKey"
echo "UserName of the server on which a new user has be created		: 	$internalServerUser"
echo "IP of the server on which a new user has be created			:	$internalServerIP"

if [ $showListOfJobs == "yes" ]
then

	printf "\033[1;31mLogging into: "$internalServerPemKey" "$internalServerUser"@"$internalServerIP"\033[0m\n"
	ssh -i "$internalServerPemKey" "$internalServerUser"@"$internalServerIP" << HERE
		printf "\033[1;33m------------------------------------------------------------------After ssh"
		echo -e "\033[0m" #reset color
		echo "after ssh"
		hostname -I
		hostname
		echo "Changing user to root"
		sudo su << EOF
			echo "User Switched To;"
			whoami
			printf "\033[1;33m------------------------------------------------------------------List of Cron Jobs Before Deletion"
			echo -e "\033[0m" #reset color
			crontab -l | cat -n
			printf "\033[1;31mExiting from         ---> "$internalServerPemKey" "$internalServerUser"@"$internalServerIP"\033[0m\n"
EOF
HERE
fi


echo "Enter Cron Job Line Number to be removed"
read lineNumber
printf "\033[1;31mLogging into: "$internalServerPemKey" "$internalServerUser"@"$internalServerIP"\033[0m\n"
ssh -i "$internalServerPemKey" "$internalServerUser"@"$internalServerIP" << HERE
	printf "\033[1;33m------------------------------------------------------------------After ssh"
	echo -e "\033[0m" #reset color
	echo "after ssh"
	hostname -I
	hostname
	#sleep 2
	echo "Changing user to root"
	sudo su << EOF
		echo "User Switched To;"
		whoami
		printf "\033[1;33m------------------------------------------------------------------List of Cron Jobs Before Deletion"
		echo -e "\033[0m" #reset color
		crontab -l | cat -n
		crontab -l | sed -e "$lineNumber"d >crontab.tmp
		crontab crontab.tmp && rm -f crontab.tmp
		printf "\033[1;33m------------------------------------------------------------------Updated List of Cron Jobs"
		echo -e "\033[0m" #reset color
		crontab -l | cat -n
		printf "\033[1;31mExiting from         ---> "$internalServerPemKey" "$internalServerUser"@"$internalServerIP"\033[0m\n"
EOF
HERE

执行 Shell 脚本删除 Cronjob

要删除 Cronjob,请执行该 shell 脚本。它将列出 Ubuntu 18.04 EC2 实例上所有可用的 Cronjob。然后你可以选择要删除的任务,脚本将为你完成删除操作。

./remove-cronjob.sh -K ~/Downloads/example-test.pem -U ubuntu -I ec2-15-236-64-128.eu-west-3.compute.amazonaws.com -l yes

使用 Shell 脚本在 AWS Linux EC2 实例增删定时任务

现在,你可以再次执行相同的脚本,列出 EC2 实例中的 Cronjob。

./remove-cronjob.sh -K ~/Downloads/example-test.pem -U ubuntu -I ec2-15-236-64-128.eu-west-3.compute.amazonaws.com -l yes

使用 Shell 脚本在 AWS Linux EC2 实例增删定时任务

你也可以从 EC2 实例本身检查 Cronjob。

ssh -i ~/Downloads/example-test.pem 
[email protected]
sudo -i
crontab -l

使用 Shell 脚本在 AWS Linux EC2 实例增删定时任务

结论

在本文中,我们了解了用于从 Ubuntu EC2 实例添加和删除 Cronjob 的 Shell 脚本。这将有助于自动化添加或删除 Cronjob 的手动任务,并避免因手动操作而可能产生的潜在人为错误。