#!/bin/bash
if [ $(id -u) -ne 0 ];then
echo "需要root用户执行";exit 1
fi
if grep -qi "centos" /etc/os-release ; then
OS='centos'
elif grep -qi "ubuntu" /etc/os-release ; then
OS='ubuntu'
else
echo "只支持ubuntu和centos"
fi
if [ "$OS" = "ubuntu" ];then
conf_file=$(dpkg -L ntp | grep /etc | grep ntp.conf)
if ! dpkg-query --show --showformat='${Status}' ntp | grep -q "install ok installed" ;then
echo "请先安装ntp服务";exit 1
fi
else
conf_file=$(rpm -ql ntp | grep /etc | grep ntp.conf)
if ! rpm -q ntp &> /dev/null ; then
echo "请先安装ntp服务";exit 1
fi
fi
if [ ! -f ${conf_file} ];then
echo "${conf_file} 文件不存在,请检查";exit 1
fi
cp ${conf_file} ${conf_file}.bak
cat > ${conf_file} <<EOF
# /etc/ntp.conf, configuration for ntpd; see ntp.conf(5) for help
driftfile /var/lib/ntp/ntp.drift
# Leap seconds definition provided by tzdata
leapfile /usr/share/zoneinfo/leap-seconds.list
# Enable this if you want statistics to be logged.
#statsdir /var/log/ntpstats/
statistics loopstats peerstats clockstats
filegen loopstats file loopstats type day enable
filegen peerstats file peerstats type day enable
filegen clockstats file clockstats type day enable
# 将本地时钟配置为NTP服务器的时间源。
server 127.127.1.0
# 设置优先同步本地时间
fudge 127.127.1.0 stratum 10
# 禁止其他服务器对NTP服务器进行配置操作,但是允许其他服务器进行时间同步
restrict -4 default kod notrap nomodify nopeer noquery
restrict -6 default kod notrap nomodify nopeer noquery
# 允许本地主机进行更详细的NTP服务器访问
# 如果注释掉了,不能再本机使用 ntpq -p 命令查看NTP服务器的状态和同步信息。
restrict 127.0.0.1
restrict ::1
# default 允许来自任何IP地址的主机进行时间同步
# restrict 192.168.0.0 mask 255.255.255.0 notrap nomodify noquery
restrict default notrap nomodify noquery
EOF
if [ ${OS} = "ubuntu" ];then
systemctl enable ntp.service &> /dev/null
if systemctl restart ntp.service &> /dev/null ;then
echo -e "重启成功"
fi
else
systemctl enable ntpd.service &> /dev/null
if systemctl restart ntpd.service &> /dev/null ;then
echo -e "重启成功"
fi
fi
if ss -tuln | grep -q ':123 '; then
echo "ntp 配置成功"
else
echo "ntp 配置失败"
fi
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了