Linux 时间设置常用命令(收藏版)
日常运维、服务器校准、日志时间对齐必备,一次整理全搞定!
一、查看当前时间
date # 查看系统时间
hwclock # 查看硬件时钟(BIOS时间)
timedatectl # 查看时间/时区/NTP状态
二、临时设置系统时间(重启失效)
# 设置日期时间
date -s "2026-03-18 15:30:00"
# 只改日期
date -s "2026-03-18"
# 只改时间
date -s "15:30:00"
三、系统时间 ↔ 硬件时钟同步
# 系统时间写入硬件时钟
hwclock -w
# 硬件时钟同步到系统
hwclock -s
四、时区设置(推荐)
# 列出所有时区
timedatectl list-timezones
# 设为上海时区(中国标准时间)
timedatectl set-timezone Asia/Shanghai
五、自动同步时间(最稳方案)
# 开启NTP自动同步
timedatectl set-ntp true
# 关闭NTP
timedatectl set-ntp false
六、CentOS/RHEL 安装chrony同步时间
yum install -y chrony
systemctl enable --now chronyd
chronyc sources # 查看同步状态
七、Debian/Ubuntu 安装ntp/chrony
apt update
apt install -y chrony
systemctl enable --now chrony
小总结
- 避免踩坑:优先用
timedatectl,少手动硬写时间
CentOS 7 搭建 NTP 时间服务器(服务端+客户端 完整版)
适合内网多服务器统一时间校准,一步到位,复制即用!
一、先说明
CentOS 7 **默认推荐 chrony**(比传统 ntp 更快、更稳),但很多老业务仍用 ntp,两者均可:
方案1:传统 NTP 服务(ntpd)
一、服务端配置(时间源服务器)
1. 安装
yum install -y ntp ntpdate
2. 编辑配置文件
vi /etc/ntp.conf
替换成以下内容(内网可用):
# 上层时间服务器(阿里云)
server ntp.aliyun.com iburst
server ntp1.aliyun.com iburst
# 允许本地时钟作为 fallback
server 127.127.1.0
fudge 127.127.1.0 stratum 10
# 允许内网网段同步(修改为你的内网网段)
restrict 192.168.1.0 mask 255.255.255.0 nomodify notrap
# 允许本地操作
restrict 127.0.0.1
restrict ::1
# 日志与数据
driftfile /var/lib/ntp/drift
keys /etc/ntp/keys
3. 启动并开机自启
systemctl start ntpd
systemctl enable ntpd
4. 防火墙放行(必须)
firewall-cmd --permanent --add-service=ntp
firewall-cmd --reload
5. 查看状态
ntpq -p
systemctl status ntpd
二、客户端配置(同步服务端时间)
1. 安装
yum install -y ntp ntpdate
2. 指向你的服务端 IP
vi /etc/ntp.conf
注释原有 server,添加:
server 192.168.1.100 iburst # 你的服务端IP
3. 先手动同步一次
ntpdate 192.168.1.100
4. 启动服务
systemctl start ntpd
systemctl enable ntpd
方案2:推荐方案 Chrony(CentOS7 原生)
一、服务端
1. 安装
yum install -y chrony
2. 配置
vi /etc/chrony.conf
修改内容:
# 上层时间源
server ntp.aliyun.com iburst
# 允许内网同步
allow 192.168.1.0/24
# 无法同步外网时,使用本地时间
local stratum 10
3. 启动+防火墙
systemctl start chronyd
systemctl enable chronyd
firewall-cmd --permanent --add-service=ntp
firewall-cmd --reload
4. 查看同步状态
chronyc sources -v
二、客户端(Chrony)
1. 安装
yum install -y chrony
2. 指向服务端
vi /etc/chrony.conf
server 192.168.1.100 iburst # 服务端IP
3. 启动
systemctl start chronyd
systemctl enable chronyd
4. 查看同步
timedatectl
chronyc tracking
常用排查命令(收藏)
# 查看时间是否同步
timedatectl
# 立即手动同步
ntpdate 192.168.1.100
# 查看 ntp 服务状态
systemctl status ntpd
systemctl status chronyd
# 查看同步源
ntpq -p
chronyc sources
🔥 CentOS 7 内网时间同步方案✅ 传统 NTP 服务(兼容老系统) ✅ 推荐 Chrony 服务(更快更稳) ✅ 服务端 + 客户端 完整配置 ✅ 防火墙一键放行 ✅ 企业内网统一时间标准