利用/var/log/auth.log
时间: 2023-07-08 08:54:25 浏览: 133
除了使用inotify监控/etc/passwd文件外,也可以利用/var/log/auth.log日志文件来实时获取新增用户。auth.log文件记录了系统的用户认证和授权信息,包括用户登录、密码修改、sudo使用等等。
具体实现步骤如下:
1. 使用系统函数open()打开/var/log/auth.log日志文件,并使用lseek()将文件指针定位到文件末尾。
2. 使用系统函数read()读取文件内容,并处理新增用户的日志信息。
3. 在处理日志信息时,可以使用正则表达式匹配新增用户的信息,从而得知新增用户的信息。
下面是一个简单的示例代码:
```
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <regex.h>
#define BUF_SIZE 1024
int main(int argc, char **argv) {
int fd, n;
char buf[BUF_SIZE];
off_t off;
regex_t reg;
regmatch_t match[2];
fd = open("/var/log/auth.log", O_RDONLY);
if (fd < 0) {
perror("open");
exit(EXIT_FAILURE);
}
off = lseek(fd, 0, SEEK_END);
while (1) {
n = read(fd, buf, BUF_SIZE);
if (n < 0) {
perror("read");
exit(EXIT_FAILURE);
}
if (n == 0) {
usleep(1000000); // wait for new data
continue;
}
if (regcomp(®, "useradd: new user: name=([^,]+)", REG_EXTENDED) != 0) {
perror("regcomp");
exit(EXIT_FAILURE);
}
if (regexec(®, buf, 2, match, 0) == 0) {
char *name = strndup(&buf[match[1].rm_so], match[1].rm_eo - match[1].rm_so);
printf("New user added: %s\n", name);
free(name);
}
regfree(®);
off += n;
lseek(fd, off, SEEK_SET);
}
close(fd);
return 0;
}
```
这段代码可以实时监控/var/log/auth.log日志文件的新增用户信息,并输出新增用户的用户名。需要注意的是,我们使用正则表达式匹配日志信息时,需要使用regcomp()函数编译正则表达式,并使用regexec()函数执行正则表达式匹配。同时,为了避免重复输出新增用户信息,我们在每次读取日志文件内容时,将文件指针定位到文件末尾,从而避免重复处理已经处理过的日志信息。
阅读全文
相关推荐


















