centos 搭建ntp

str=$(printf "%-25s" "*")
echo -e "${str// /*}"
echo -e "*\t\t\t*"
echo -e "*\tNTP 安装\t*"
echo -e "*\t\t\t*"
echo -e "${str// /*}"
#搭建ntp建议搭建在Puppet控制端
ntp=`rpm -qa | grep ntp- && echo $?`
if [[ "$ntp"x == ""x ]];then
    yum install ntp-* -y > /dev/null 2>&1
fi
#同步时间
/etc/init.d/ntpd stop > /dev/null 2>&1
ntp=`ntpdate 0.uk.pool.ntp.org && ntpdate 0.uk.pool.ntp.org && echo $?`
if [[ "$ntp" == "" ]];then
    echo 'NTP同步失败'
    echo "执行ntpdate 0.uk.pool.ntp.org检查"
    exit
fi
#写入配置文件
cat > /etc/ntp.conf << EFO
driftfile /var/lib/ntp/drift
restrict default kod nomodify notrap nopeer noquery
restrict 127.0.0.1
restrict 0.0.0.0 mask 0.0.0.0 nomodify
SYNC_HWCLOCK=yes
server time.nist.gov prefer
server 0.centos.pool.ntp.org minpoll 4 maxpoll 4 iburst
server 1.centos.pool.ntp.org minpoll 4 maxpoll 4 iburst
server 2.centos.pool.ntp.org minpoll 4 maxpoll 4 iburst
server 3.centos.pool.ntp.org minpoll 4 maxpoll 4 iburst
server 210.72.145.44
server 218.21.130.42
server  127.127.1.0
fudge 127.127.1.0 stratum 3
restrict time.nist.gov nomodify notrap noquery
restrict 0.centos.pool.ntp.org nomodify notrap noquery
restrict 1.centos.pool.ntp.org nomodify notrap noquery
restrict 2.centos.pool.ntp.org nomodify notrap noquery
restrict 3.centos.pool.ntp.org nomodify notrap noquery
restrict 210.72.145.44 nomodify notrap noquery
restrict 218.21.130.42 nomodify notrap noquery
includefile /etc/ntp/crypto/pw
keys /etc/ntp/keys
disable monitor
EFO
if [ $? != 0 ];then
    echo "写入失败"
    exit
fi
#启动
/etc/init.d/ntpd start
ntp=`/etc/init.d/ntpd status | grep -Eo stopped`
if [ "$ntp" == "stopped" ];then
    echo "启动失败"
    echo "执行/etc/init.d/ntpd status检查并启动"
    exit
fi
chkconfig ntpd on > /dev/null 2>&1
ntp=`chkconfig --list ntpd | awk '{print $4,$5,$6}' | sed -e 's/://g' -e 's/[2-4\]//g' -e 's/ /\n/g'|uniq | grep -v 'on'`
if [[ "$ntp" != "" ]];then
    echo "设置NTP开机启动失败"
    echo "执行chkconfig --list ntpd检查"
    exit
fi
ntp=`ntpq -p | sed '1,2d' | awk '{print $9}'`
for i in ntp
do
    if [ x"$i" == x'' ];then
        echo "时间同步有问题"
        echo "执行ntpq -p检查"
        exit
    fi
done
#将ntp写入crontab
#ntp
ntp=`grep -q "NTP" /etc/crontab && echo $?`
if [[ "$ntp" != "0" ]];then
    echo "#NTP" >> /etc/crontab
    echo "0  1 * * * root /usr/sbin/ntpdate time-b.nist.gov >/dev/null 2" >> /etc/crontab
    service crond reload
fi

 

posted @ 2018-03-16 15:29  IT菜鸟园  阅读(371)  评论(0编辑  收藏  举报