Find which files are read or written to
I want to see which files are read or written to.
Is there any program or a command for that? I can remember I used this method to hunt down viruses and malware hiding locations when I used windows a few years back.
That program is lsof
("List open files").
-
If you just open a Terminal and type
lsof
, you get a huge list of all open files, instead, limit it to one command by doing:lsof -c gnome-terminal
-
You can also restrict your search to a specific directory by typing
lsof -c gnome-terminal -a +D /tmp
-
Or list all open files in one specific directory, including what application has opened it:
lsof /dev/urandom
Remember that some processes are started by the superuser root, you may need to put sudo
in front of your command to get more information about such processes' open files.
To narrow down your search, you can grep
specific lines, i.e.:
lsof /dev/urandom | grep chrome
-
The
FD
(File Descriptor) column of the output gives you information about the purpose of the program opening the file (not necessarily what's happening to it at the moment):-
r
means the file is opened for reading -
w
means the file is opened for writing -
u
means the file is opened for both reading and writing
-
For more details, consult the manual page (man lsof
). Also, if you need to look up any of the files and directories, the Linux Filesystem Hierarchy Standard is very helpful.
As a complete over-kill option, but one that works in real-time, you can use inotify:
sudo inotifywait -m -r /
Note that this will consume a great deal of memory, and take a long time to set up. As the manpage says:
-r, --recursive
Watch all subdirectories of any directories passed as arguments.
Watches will be set up recursively to an unlimited depth. Sym‐
bolic links are not traversed. Newly created subdirectories
will also be watched.
Warning: If you use this option while watching the root direc‐
tory of a large tree, it may take quite a while until all ino‐
tify watches are established, and events will not be received in
this time. Also, since one inotify watch will be established
per subdirectory, it is possible that the maximum amount of ino‐
tify watches per user will be reached. The default maximum is
8192; it can be increased by writing to /proc/sys/fs/ino‐
tify/max_user_watches.
This also doesn't tell you what process is messing with files, but it may help identify changes as they happen. Using "-e open" may help reduce some of the noise on a really busy system.