誰是記錄者?
我使用的是ubuntu,想通過編程手段查閱各個使用者登陸和登出的詳細記錄,那麼首先我得知道操作對象是誰,要對哪個檔案下手,那麼問題來了——這些記錄是儲存在哪個檔案裡?
搜尋記錄者
尋找文檔可以通過man命令,它有個-k的參數,很是有用,格式為:
man -k printf
在簡短描述和手冊文檔中搜尋與printf匹配的記錄並列印,所以我們輸入
man -k login
執行之後會列印出一些記錄,查閱後我們定位到下面幾條記錄:
utmp (5) - login records
utmpx (5) - login records
wtmp (5) - login records
然後,我們要引用括弧內的序號查閱該文檔
man 5 utmp
man 5 utmpx
man 5 wtmp
發現都指向一份文檔,那麼它到底是不是我們要找的檔案呢?
是或不是
The utmp file allows one to discover information about who is currently using the system. There may be more users currently using the system,because not all programs use utmp logging.
這是文檔的簡介,以4級水平的我粗略翻譯,它是說utmp檔案允許用來瞭解目前系統使用者的資訊,可能目前有更多使用系統的使用者,因為並不是所有的程式使用utmp登陸
概要後面還有對在登陸發生各種情況時記錄情況,我想八九不離十,應該就是它們了。
區別
使用utmp、wtmp、utmpx都需要#include <utmp.h>,它們的檔案是二進位的,內容實際上是一個utmp結構體序列,該結構體聲明在utmp.h檔案中,結構成員記錄了詳細的使用者登陸資訊,它們的區別在於:
wtmp記錄了所有登陸和登出記錄,格式與用空使用者名稱標記登出的utmp很相似,登陸也好登出也好都是往裡面添加資料;
而utmp通過修改檔案內容,登陸的時候添加記錄,登出時刪除記錄,只記錄當前使用系統的使用者資訊;
utmpx它與utmp結構體相似,區別在於POSIX.1沒有指定utmp結構,而是定義為utmpx,它定義了ut_type、ut_pid、ut_line、ut_id、ut_user和ut_tv,並沒有設定ut_line、ut_user欄位的長度。
使用
源自《Unix\Linux編程實踐教程(附光碟片)》 中的一段代碼:
#include <stdio.h>
#include <fcntl.h>
#include <sys/types.h>
#include <utmp.h>
#define NRECS 16
#define NULLUT ((struct utmp*)NULL)
#define UTSIZE (sizeof(struct utmp))
static char utmpbuf[NRECS * UTSIZE]; //容器
static int num_recs; //儲存數量
static int cur_rec; //下一個
static int fd_utmp = -1; //讀取fd
utmp_open(char* filename)
{
fd_utmp = open(filename, O_RDONLY);
cur_rec = num_recs = 0;
return fd_utmp;
}
struct utmp* utmp_next()
{
struct utmp* recp;
if(fd_utmp == -1)
return NULLUT;
if(cur_rec == num_recs && utmp_reload() == 0)
return NULLUT;
recp = (struct utmp*)&utmpbuf[cur_rec * UTSIZE];
cur_rec++;
return recp;
}
int utmp_reload(){
int amt_read;
amt_read = read(fd_utmp, utmpbuf, NRECS*UTSIZE);
num_recs = amt_read / UTSIZE;
cur_rec = 0;
return num_recs;
}
utmp_close(){
if(fd_utmp != -1)
close(fd_utmp);
}