温馨提示×

centos readdir怎监听

小樊
43
2026-09-18 07:33:32
栏目: 智能运维

在 CentOS 上,“监听 readdir”通常有两种理解,下面分别说明:


一、监听某个目录被“读取(readdir)”的动作(谁在列目录)

方法 1:使用 inotify(最常用,但不能精确监听 readdir)

inotify 不能直接监听 readdir,只能监听:

  • 创建
  • 删除
  • 修改
  • 属性变化
yum install inotify-tools
inotifywait -m /path/to/dir

⚠️ 注意:
ls、readdir 不会触发 inotify 事件


方法 2:使用 auditd(推荐 ✅)

auditd 可以监控 系统调用级别,包括 readdir

1. 安装 audit

yum install audit
systemctl start auditd
systemctl enable auditd

2. 添加规则(监控目录读取)

auditctl -w /path/to/dir -p r -k dir_read
  • -w:监控路径
  • -p r:读权限(包含 readdir)
  • -k:自定义关键字

3. 查看日志

ausearch -k dir_read

或实时看:

tail -f /var/log/audit/audit.log

示例日志:

type=SYSCALL msg=audit(...): arch=c000003e syscall=217 ...

(syscall=217 是 getdents / readdir)


方法 3:使用 bpftrace(高级 ✅)

适合开发 / 内核级监控

bpftrace -e '
tracepoint:syscalls:sys_enter_getdents* {
    printf("%s %s\n", comm, str(args->pathname));
}
'

二、在 C 程序中“监听” readdir(编程角度)

如果你是 写程序,想拦截 readdir:

方法 1:LD_PRELOAD 劫持

#define _GNU_SOURCE
#include <dirent.h>
#include <string.h>

struct dirent *readdir(DIR *dirp) {
    static typeof(readdir) *real = NULL;
    if (!real) real = dlsym(RTLD_NEXT, "readdir");
    struct dirent *d = real(dirp);
    if (d) printf("readdir: %s\n", d->d_name);
    return d;
}

编译:

gcc -shared -fPIC hook.c -o hook.so -ldl

运行:

LD_PRELOAD=./hook.so ls

三、总结建议

需求 推荐方案
监控谁读了目录 auditd
实时列目录变化 inotify(非 readdir)
开发/调试 bpftrace
程序级拦截 LD_PRELOAD

如果你能说清楚:

  • 是 系统安全监控
  • 还是 程序开发
  • 还是 排查某个进程读目录

我可以给你更精确的方案。

0 踩