ntp服务端快速搭建

发布时间 2023-09-11 16:44:54作者: 背对背依靠
#!/bin/bash

if [ $(id -u) -ne 0 ];then
    echo "需要root用户执行该脚本"
    exit 1
fi

# Determine package manager
if command -v dpkg &> /dev/null; then
    PKG_CHECK="dpkg-query -W"
    CONFIG_FILE="/etc/ntp.conf"
    SERVICE_CMD="systemctl"
elif command -v rpm &> /dev/null; then
    PKG_CHECK="rpm -q"
    CONFIG_FILE="/etc/ntp/ntp.conf"
    SERVICE_CMD="systemctl"
else
    echo "不支持的操作系统"
    exit 1
fi

# ntp服务检查
if ! $PKG_CHECK ntp &> /dev/null; then
    echo "请先安装ntp服务"
    exit 1
fi

# check config file
if [ ! -f $CONFIG_FILE ]; then
    echo "配置文件 $CONFIG_FILE 不存在."
    exit 1
fi

# ntp配置
sed -i -r 's/^(pool.*)/# \1/' $CONFIG_FILE
sed -i -r 's/^(restrict -4 default kod notrap nomodify nopeer noquery) limited/\1/' $CONFIG_FILE
sed -i -r 's/^(restrict -6 default kod notrap nomodify nopeer noquery) limited/\1/' $CONFIG_FILE
sed -i -r '/^restrict source notrap nomodify noquery/s/source/default/' $CONFIG_FILE

# 时间服务器配置
if ! grep -q "127.127.1.0" $CONFIG_FILE; then
    echo -e "server 127.127.1.0\nfudge 127.127.1.0 stratum 10" >> $CONFIG_FILE
fi

if  $SERVICE_CMD restart ntp.service; then
    echo "ntp服务端配置成功"
else
    echo "请检查ntp服务端的配置"
fi