定时更新Linux操作系统的系统时间

前期说明

场景:服务器可以正常访问互联网的情况下
系统: 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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值