本文目录导读:

在不同操作系统中,获取上次关机时间的方法不同,以下提供 Windows、Linux 和 macOS 的脚本实现。
Windows(PowerShell)
Windows 系统的事件日志中记录了关机事件(事件ID 1074 或 6006),以下脚本提取最近一次关机时间:
# 获取最近一次正常关机事件(事件ID 1074 通常由用户或程序发起)
$shutdownEvent = Get-WinEvent -FilterHashtable @{LogName='System'; ID=1074} -MaxEvents 1 2>$null
if ($shutdownEvent) {
Write-Output "上次关机时间: $($shutdownEvent.TimeCreated)"
} else {
# 若没有1074事件(例如意外断电),尝试查找6006(服务停止,通常与关机相关)
$shutdownEvent = Get-WinEvent -FilterHashtable @{LogName='System'; ID=6006} -MaxEvents 1
if ($shutdownEvent) {
Write-Output "上次关机时间(来自6006事件): $($shutdownEvent.TimeCreated)"
} else {
Write-Output "无法找到关机事件"
}
}
说明:
- 事件ID
1074:记录用户发起关机、重启(包含原因)。 - 事件ID
6006:表示系统日志服务关闭(通常跟随正常关机)。 - 如果系统未记录日志(如事件日志被清理),可能无法获取。
Linux(Bash)
Linux 中可以通过 last 命令或 /var/log/wtmp 文件查看系统启动/关机记录。
#!/bin/bash
# 获取上次关机时间(从wtmp日志)
last -x | grep shutdown | head -n 1 | awk '{print $5, $6, $7, $8, $9}'
或者更精确地解析 last -x 输出:
#!/bin/bash
# 显示最后一次关机的具体时间
last -x | grep -E 'shutdown|system shutdown' | awk '
{
# 输出字段5-9(日期和时间部分)
for (i=5; i<=NF; i++) printf "%s ", $i
print ""
}' | head -1
如果系统使用 journalctl(systemd 系统),也可以:
journalctl --list-boots --no-pager | tail -2 | head -1 | awk '{print $3, $4}'
# 注意:需逆向推断关机时间(关机发生在下一次启动之前)
更可靠的方法(使用 last -x 示例输出):
$ last -x | grep shutdown shutdown system down 3.10.0-957.el7.x Wed Mar 15 17:30 - 17:30 (00:00)
上面显示的是关机时间“Wed Mar 15 17:30”。
注意:last 读取 /var/log/wtmp,某些系统可能不记录关机,或日志被轮转。
macOS(Bash)
macOS 同样可以使用 last 命令,但关机事件记录在 /var/log/wtmp(旧版)或 log show(新版)。
使用 last(兼容旧版)
#!/bin/bash
# 获取最近一次关机时间
last -x | grep shutdown | head -1 | awk '{print $3, $4, $5, $6}'
使用 log show(macOS 10.12+)
#!/bin/bash
# 从统一日志中提取上次关机事件
log show --predicate 'eventMessage contains "shutdown" or eventMessage contains "System shutdown"' --last 2d --style syslog 2>/dev/null | \
grep -i 'system shutdown' | tail -1 | awk '{print $1, $2, $3, $4, $5}'
说明:macOS 的 Unified Logging(统一日志)可能不直接记录“正常关机”为易读格式,有时需搜索 shutdownNow 或 powerd 相关条目。
跨平台方案(Python)
如果需要跨平台(Windows/Linux/macOS),推荐使用 Python 脚本:
import platform
import subprocess
import sys
def get_last_shutdown_windows():
try:
# 使用PowerShell查询事件ID 1074
cmd = 'powershell -Command "Get-WinEvent -FilterHashtable @{LogName=\'System\'; ID=1074} -MaxEvents 1 | Select-Object -ExpandProperty TimeCreated"'
result = subprocess.run(cmd, shell=True, capture_output=True, text=True, timeout=5)
if result.returncode == 0 and result.stdout.strip():
return result.stdout.strip()
# 尝试事件ID 6006
cmd = 'powershell -Command "Get-WinEvent -FilterHashtable @{LogName=\'System\'; ID=6006} -MaxEvents 1 | Select-Object -ExpandProperty TimeCreated"'
result = subprocess.run(cmd, shell=True, capture_output=True, text=True, timeout=5)
if result.returncode == 0 and result.stdout.strip():
return result.stdout.strip()
except:
pass
return "无法获取"
def get_last_shutdown_linux():
try:
result = subprocess.run(['last', '-x'], capture_output=True, text=True, timeout=5)
if result.returncode == 0:
for line in result.stdout.split('\n'):
if 'shutdown' in line and 'system down' in line:
# 提取时间部分(字段5-9)
parts = line.split()
if len(parts) >= 9:
return ' '.join(parts[4:9])
# 备选:尝试journalctl
result = subprocess.run(['journalctl', '--list-boots', '--no-pager'], capture_output=True, text=True, timeout=5)
boots = result.stdout.strip().split('\n')
if len(boots) >= 2:
last_boot = boots[-1].split()
if len(last_boot) >= 4:
return last_boot[3] # 上一启动时间(关机在此之后)
except:
pass
return "无法获取"
def get_last_shutdown_macos():
try:
result = subprocess.run(['last', '-x'], capture_output=True, text=True, timeout=5)
if result.returncode == 0:
for line in result.stdout.split('\n'):
if 'shutdown' in line:
parts = line.split()
if len(parts) >= 6:
return ' '.join(parts[2:6])
except:
pass
return "无法获取"
if __name__ == '__main__':
system = platform.system()
if system == 'Windows':
print("上次关机时间:", get_last_shutdown_windows())
elif system == 'Linux':
print("上次关机时间:", get_last_shutdown_linux())
elif system == 'Darwin':
print("上次关机时间:", get_last_shutdown_macos())
else:
print("不支持的系统")
关键提示
- Windows:依赖系统日志,如果日志被清除或系统异常断电(无事件记录),可能无法获得。
- Linux/macOS:
last读取二进制日志/var/log/wtmp,此文件可能因日志轮转而丢失旧记录。 - 权限:读取系统日志可能需要管理员/root权限(特别是在 Linux 和 macOS 上)。
- 时间格式:输出可能因系统 locale 设置不同而不同,建议使用 ISO 8601 格式以保持一致性。
选择适合你操作系统的方法即可。