#!/bin/bash
if [ $(id -u) -ne 0 ];then
echo "需要root用户执行";exit 1
fi
# release
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
# installed
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
# confige
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