xinlugang 2020-02-18
一、前期说明
场景:服务器可以正常访问互联网的情况下
方法:通过shell+crond来让其实现每隔5分钟更新一次系统时间
二、shell脚本
脚本名称:update_os_time.sh
存放位置: /server/scripts/
注意事项:请检查是否存在ntpdate命令,若没有,则用yum install ntpdate -y命令进行安装
#!/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三、定时任务中的设置
[ ~]# 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