萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 作業系統 >  >> Linux 教學

Linux C 語言讀取 /var/log/wtmp 取得系統關機時間記錄

利用 <utmp.h> 提供的 getutent() 遍歷 /var/log/wtmp (或 /var/log/btmp) 中的 utmp 結構,篩選 ut_user == "shutdown" 的記錄,即可取得歷次關機時間。適用於安全稽核、系統可用性分析。

完整程式碼


#include <stdio.h>
#include <stdlib.h>
#include <utmp.h>
#include <time.h>
#include <string.h>

int main() {
    struct utmp *u;
    FILE *fp = fopen("shutdown_note", "w+");
    if (!fp) { perror("fopen"); return 1; }

    utmpname("/var/log/wtmp");  // 指定 wtmp 路徑
    setutent();                 // 重置游標到開頭

    while ((u = getutent()) != NULL) {
        if (strncmp(u->ut_user, "shutdown", 8) == 0) {
            time_t t = u->ut_tv.tv_sec;
            fprintf(fp, "%s time: %s", u->ut_user, ctime(&t));
        }
    }
    endutent();
    fclose(fp);
    return 0;
}

關鍵點說明

  • utmpname():指定要讀取的 utmp/wtmp 檔案路徑 (預設 _PATH_UTMP)。
  • setutent()/endutent():重置/關閉 utmp 存取游標。
  • getutent():逐筆讀取下一筆記錄,回傳指向靜態緩衝區的指標。
  • ut_user:使用者名稱欄位,關機記錄固定為 "shutdown"。
  • ut_tv.tv_sec:時間戳 (time_t,秒數),搭配 ctime() 轉為可讀字串。
  • 需 root 權限讀取 /var/log/wtmp (通常 644 root:utmp)。

擴充應用

  • 同樣方法可分析 ut_type 為 BOOT_TIME、RUN_LVL、LOGIN_PROCESS、USER_PROCESS、DEAD_PROCESS 等記錄。
  • 搭配 last、lastb、lastlog 指令可快速查看而不寫程式。
  • 嵌入式系統無 wtmp 時,可自行在關機腳本中寫入時間戳至自訂檔案。
copyright © 萬盛學電腦網 all rights reserved