在 Ubuntu 系统中,有时我们需要了解系统上次重启的日期和时间。这在系统管理、故障排除和日志审计中尤为重要。本文将详细介绍多种方法来查询上次 Ubuntu 重启的时间,并解释每种方法的背后原理。
uptime
命令查询系统运行时间uptime
命令可以显示系统已经运行的时间。这是最快速且最简单的方法之一。
uptime
uptime
命令的输出通常如下所示:
12:34:56 up 5 days, 4:23, 3 users, load average: 0.03, 0.02, 0.00
12:34:56
:当前时间up 5 days, 4:23
:系统已经运行的时间,具体为5天4小时23分钟3 users
:当前登录的用户数量load average: 0.03, 0.02, 0.00
:系统的负载平均值通过减去系统运行时间,可以推算出系统的重启时间。
假设当前时间为 2024-05-21 12:34:56
,系统已经运行 5 days, 4:23
。
重启时间为:2024-05-21 12:34:56 - 5 days 4:23
。
使用 Python 脚本计算:
from datetime import datetime, timedelta
current_time = datetime.strptime("2024-05-21 12:34:56", "%Y-%m-%d %H:%M:%S")
uptime = timedelta(days=5, hours=4, minutes=23)
reboot_time = current_time - uptime
print("Reboot time:", reboot_time)
输出结果:
Reboot time: 2024-05-16 08:11:56
last
命令查看系统重启日志last
命令可以显示最近的登录和重启事件。
last reboot
reboot system boot 5.4.0-104-generic Fri May 16 08:11 - 12:34 (5+04:23)
reboot
:事件类型system boot
:系统启动5.4.0-104-generic
:内核版本Fri May 16 08:11
:重启时间12:34
:当前时间(5+04:23)
:系统运行时间who
命令检查系统启动时间who
命令带有 -b
选项可以显示系统的启动时间。
who -b
system boot 2024-05-16 08:11
system boot
:系统启动2024-05-16 08:11
:系统启动时间系统日志文件中也记录了系统的启动和重启信息。
journalctl --boot
-- Logs begin at Fri 2024-05-16 08:11:34 UTC, end at Fri 2024-05-21 12:34:56 UTC. --
May 16 08:11:34 hostname kernel: Linux version 5.4.0-104-generic (buildd@lgw01-amd64-058) (gcc version 9.3.0 (Ubuntu 9.3.0-17ubuntu1~20.04)) #117-Ubuntu SMP Fri Apr 16 02:36:12 UTC 2024 (Ubuntu 5.4.0-104.117-generic 5.4.105)
systemd
工具查询重启时间systemd-analyze
命令可以显示系统的启动时间。
systemd-analyze
Startup finished in 1.234s (kernel) + 2.345s (userspace) = 3.579s
graphical.target reached after 2.456s in userspace
1.234s (kernel)
:内核启动时间2.345s (userspace)
:用户空间启动时间3.579s
:总启动时间可以编写脚本自动记录重启时间,便于查询。
#!/bin/bash
logfile="/var/log/reboot_time.log"
if [[ ! -f $logfile ]]; then
sudo touch $logfile
sudo chmod 666 $logfile
fi
reboot_time=$(who -b | awk '{print $3, $4}')
echo "Last reboot time: $reboot_time" | sudo tee -a $logfile
对于不习惯使用命令行的用户,可以使用图形界面工具。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。