ntp服务端快速搭建脚本

#!/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

posted on   背对背依靠  阅读(30)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

点击右上角即可分享
微信分享提示