侧边栏壁纸
博主头像
liveJQ博主等级

沒有乐趣,何来开始

  • 累计撰写 145 篇文章
  • 累计创建 60 个标签
  • 累计收到 2 条评论

Linux 设置时区和NTP

liveJQ
2021-11-28 / 0 评论 / 0 点赞 / 600 阅读 / 2,499 字 / 正在检测是否收录...
广告 广告

UTC:协调世界时,是经过平均太阳时(以格林威治时间 GMT 为准)、地轴运动修正后的新时标以及以秒为单位的国际原子时所综合精算而成,全球通用。其它标准时间都是参考的 UTC,例如: CST(北京时间),UTC+8:00;AST(大西洋标准时间),UTC-4:00,主要用于北美。

时区

Linux 时区设置基本通用,这里以 Ubuntu 20.04 为例

方式一

查看本地的时间设置

timedatectl && ll /etc/localtime && cat /etc/timezone

列出可用的时区

timedatectl list-timezone

设置中国时区东八区

timedatectl set-timezone Asia/Shanghai

旧版本系统会默认将硬件时钟(RTC)设为本地时间(查看的时候一般有警告出现),更改时区后会出现各种问题,不够准确,所以最好将其改为 UTC 时间。

timedatectl set-local-rtc 0

执行 hwclock 可以查看硬件时间(与之对应的为软件时间,由系统根据1970年01月01日至今计算出的总秒数)。当机器重启或无法联网同步时间时,可以直接从硬件上读取时间。至于 timedatectl 中显示的 RTC 为何与这里的 hwclock 显示的时间不一致,是因为当调用上面的命令时,会自动将系统时间同步至 RTC,而 timedatectl 中的 RTC 则保持与 UTC 相同。

方式二

通过执行 tzselect 命令生成时区配置(并非真的设置时区),然后将其写入到 .profile 文件,重新登入即可生效,效果类似如下:

cat << EOF >> ~/.profile
TZ='Asia/Shanghai'; export TZ
EOF

方式三

这种方式其实是第二种的补充,也就是真的可以通过 GUI 的方式进行时区选择,然后直接生效。

dpkg-reconfigure tzdata

NTP

yum -y install ntp

NTP包括了 ntpd 服务端和 ntpdate 客户端,如果对时间同步要求不高,则可以直接进行设置,或与 Cron 搭配使用。

ntpdate ntp.aliyun.com

ntpdate 会直接设置系统时间,可能会影响某些运行中的程序,一般在系统开机后执行

ntpd 具有自我保护机制,如果本机与上源时间相差太大,可能会造成同步失败。因此,新设置的时间服务器最好先通过 ntpdate 从上源取得时间初值, 然后启动 ntpd 服务。ntpd 服务运行后,先是每 64 秒与上源服务器同步一次,根据每次同步时测得的误差值经复杂计算逐步调整自己的时间,还能逐渐修正 cpu tick。随着误差减小,逐步增加同步的间隔。每次跳动,都会重复这个调整的过程。

CentOS

ntpd 的配置文件为 /etc/ntp.conf

  • 新版关键配置
#每次校正的差值,用来调整系统或服务程序时钟
driftfile /var/lib/ntp/drift
#权限控制,禁用所有服务
restrict default nomodify notrap nopeer noquery
restrict default nomodify notrap nopeer noquery
#允许对某些IP(本地)开放
restrict 127.0.0.1
restrict ::1
#允许对一个网段开放
restrict xxx.xxx.xxx.0 mask xxx.xxx.xxx.xxx nomodify
#同步上游时间服务
server ntp.aliyun.com iburst prefer
server ntp.google.com iburst
#禁用监视器,防止 NTP 放大攻击(类似DDOS),上面做了权限控制后可以不管
disable monitor
  • 旧版关键配置

driftfile /var/lib/ntp/drift
restrict default kod nomodify notrap nopeer noquery
restrict -6 default kod nomodify notrap nopeer noquery
restrict 127.0.0.1
restrict -6 ::1

restrict xxx.xxx.xxx.0 mask xxx.xxx.xxx.xxx nomodify
server ntp.aliyun.com iburst prefect
server ntp.google.com iburst

启动并查看 NTP 服务,并设置开机自启

systemctl start ntpd && chkconfig --add ntpd && chkconfig ntpd on && timedatectl

下面的命令可以更详细的了解 NTP 服务运行情况

ntpstat && ntpq -p

Ubuntu

新版本的 Ubuntu 默认使用了更加轻量和集成化的 systemd-timesyncd 来作为 NTP 服务,默认已启动。

apt install systemd-timesyncd && systemctl unmask systemd-timesyncd && systemctl enable systemd-timesyncd && systemctl start systemd-timesyncd

若因程序或有特殊功能等的需求需要改为 ntpd,则可以直接安装相关服务。当然,与此同时,系统会自动将 systemd-timesyncd 卸载掉。

apt install ntp

停止 NTP

timedatectl set-ntp false || timedatectl set-ntp no

Chrony

apt install chrony

相关资料

  1. GMT、UTC、时区和夏令时
  2. Linux 时间之 hwclock
  3. Understanding the ntpd Configuration File
  4. What is the usage of the iburst parameter in NTP server
  5. How To Set Up Time Synchronization on Ubuntu 18.04
  6. 下一代时间同步服务 Chrony
  7. ntpd 和 ntpdate
  8. NTP协议
  9. NTP 放大攻击
0

评论区