前期说明
场景:服务器可以正常访问互联网的情况下
系统: CentOS linux
方法:通过shell+crond来让其实现每隔5分钟更新一次系统时间
SHELL脚本
在定时更新系统时间前需先校对时间:https://blog.csdn.net/weixin_43733154/article/details/106444277
脚本名称:update_os_time.sh
存放位置: /server/scripts/
注意事项:请检查是否存在ntpdate命令,若没有,则用yum install ntpdate -y命令进行安装,脚本是以root用户身份来运行
#!/bin/bash
#
# Define variables
RETVAL=0
Ntp_server=(
ntp.aliyun.com
ntp1.aliyun.com
ntp2.aliyun.com
ntp3.aliyun.com
ntp4.aliyun.com
ntp5.aliyun.com
ntp6.aliyun.com
ntp7.aliyun.com
)
# Determine the user to execute
if [ $UID -ne $RETVAL ];then
echo "Must be root to run scripts"
exit 1
fi
# Load locall functions library
[ -f /etc/init.d/functions ] && source /etc/init.d/functions
# Install ntpdate command
yum install ntpdate -y >/dev/null 2>&1
# for loop update os time
for((i=0;i<${#Ntp_server[*]};i++))
do
/usr/sbin/ntpdate ${Ntp_server[i]} >/dev/null 2>&1 &
RETVAL=$?
if [ $RETVAL -eq 0 ];then
action "Update os time" /bin/true
break
else
action "Update os time" /bin/false
continue
fi
done
# Scripts return values
exit $RTVAL
定时任务中的设置
定时任务是root用户的定时任务哈,因为脚本中限制了只能root用户执行
[root@node33 ~]# crontab -l|head -2
# Crond update os time. USER:chenliang TIME:2020-02-17
*/05 * * * * /bin/sh /server/scripts/update_os_time.sh >/dev/null 2>&1