如何实时监控进程打开的文件?

ger*_*ijk 50 process lsof open-files audit

我知道我可以查看使用过程中打开文件lsof 的时间在那一刻,我的Linux机器上。但是,进程可以如此快速地打开、更改和关闭文件,以至于我在使用标准 shell 脚本(例如watch)监视它时将无法看到它,如“在 linux 上监视打开的进程文件(实时)”中所述.

所以,我想我正在寻找一种简单的方法来审核流程并查看它在过去的时间里做了什么。如果还可以查看它(尝试)建立的网络连接并在进程有时间运行而不启动审计之前开始审计,那就太好了。

理想情况下,我想这样做:

sh $ audit-lsof /path/to/executable
4530.848254 OPEN  read  /etc/myconfig
4530.848260 OPEN  write /var/log/mylog.log
4540.345986 OPEN  read  /home/gert/.ssh/id_rsa          <-- suspicious
4540.650345 OPEN  socket TCP ::1:34895 -> 1.2.3.4:80    |
[...]
4541.023485 CLOSE       /home/gert/.ssh/id_rsa          <-- would have missed
4541.023485 CLOSE socket TCP ::1:34895 -> 1.2.3.4:80    |   this when polling
Run Code Online (Sandbox Code Playgroud)

这是否可以使用strace某些标志来看不到每个系统调用?

Use*_*ess 63

运行它

strace -e trace=open,openat,close,read,write,connect,accept your-command-here
Run Code Online (Sandbox Code Playgroud)

可能就足够了。

-o如果进程可以打印到 stderr,您将需要使用该选项将 strace 的输出放在控制台以外的其他地方。如果您的流程分叉,您还需要-for -ff

哦,你可能想-t为好,所以你可以看到,当呼叫发生。


请注意,您可能需要根据您的流程所做的调整函数调用列表 -getdents例如,我需要添加,以获得更好的示例ls

$ strace -t -e trace=open,openat,close,read,getdents,write,connect,accept ls >/dev/null
...
09:34:48 open("/etc/ld.so.cache", O_RDONLY) = 3
09:34:48 close(3)                       = 0
09:34:48 open("/lib64/libselinux.so.1", O_RDONLY) = 3
09:34:48 read(3, "\177ELF\2\1\1\0\0\0\0\0\0\0\0\0\3\0>\0\1\0\0\0@V\0\0\0\0\0\0"..., 832) = 832
09:34:48 close(3)                       = 0
...
09:34:48 open("/proc/filesystems", O_RDONLY) = 3
09:34:48 read(3, "nodev\tsysfs\nnodev\trootfs\nnodev\tb"..., 1024) = 366
09:34:48 read(3, "", 1024)              = 0
09:34:48 close(3)                       = 0
09:34:48 open("/usr/lib/locale/locale-archive", O_RDONLY) = 3
09:34:48 close(3)                       = 0
09:34:48 open(".", O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC) = 3
09:34:48 getdents(3, /* 5 entries */, 32768) = 144
09:34:48 getdents(3, /* 0 entries */, 32768) = 0
09:34:48 close(3)                       = 0
09:34:48 write(1, "file-A\nfile-B\nfile-C\n", 21) = 21
09:34:48 close(1)                       = 0
09:34:48 close(2)                       = 0
Run Code Online (Sandbox Code Playgroud)

  • 您还可以使用“-p PID”选项将“strace”附加到正在运行的进程。 (6认同)
  • 不要忘记 **`openat`** 等等! (6认同)
  • 这是进入正确的方向,谢谢!想要一个更用户友好的输出,但它可以完成工作。我可能会花时间为此编写一个具有更顶级界面的工具。我希望存在基于 ncurses 或类似“top”的工具来实时检查二进制文件的操作。 (2认同)
  • 将 `-y` 添加到“与文件描述符参数关联的 [p]rint 路径” (2认同)