Linux Monitoring – How to Find Out Which Process is Changing a File

linuxsystem-monitoring

I'm trying to find a reliable way of finding which process on my machine is changing a configuration file (/etc/hosts to be specific).

I know I can use lsof /etc/hosts to find out what processes currently have the file open, but this doesn't help because the process is obviously opening the file, writing to it, and then closing it again.

I also looked at lsof's repeat option (-r), but it seems to only go as fast as once a second, which probably won't ever capture the write in progress.

I know of a couple tools for monitoring changes to the filesystem, but in this case I want to know which process is responsible, which means catching it in the act.

Best Answer

You can use auditing to find this. If not already available, install and enable auditing for your distro.

set an audit watch on /etc/hosts

/sbin/auditctl -w /etc/hosts -p war -k hosts-file

-w watch /etc/hosts
-p warx watch for write, attribute change, execute or read events
-k hosts-file is a search key.

Wait till the hosts file changes and then use ausearch to seer what is logged

/sbin/ausearch -f /etc/hosts | more

You'll get masses of output e.g.


> time->Wed Oct 12 09:34:07 2011 type=PATH
> msg=audit(1318408447.180:870): item=0 name="/etc/hosts" inode=2211062
> dev=fd:00 mode=0100644 ouid=0 ogid=0 rdev=00:00
> obj=system_u:object_r:etc_t:s0 type=CWD msg=audit(1318408447.180:870):
> cwd="/home/iain" type=SYSCALL msg=audit(1318408447.180:870):
> arch=c000003e syscall=2 success=yes exit=0 a0=7fff73641c4f a1=941
> a2=1b6 a3=3e7075310c items=1 **ppid=7259**  **pid=7294** au id=1001 uid=0 gid=0
> euid=0 suid=0 fsuid=0 egid=0 sgid=0 fsgid=0 tty=pts0 ses=123 
> comm="touch" **exe="/bin/touch"** subj=user_u:system_r:unconfined_t:s0
> key="hosts-file"

In this case I used the touch command to change the files timstamp it's pid was 7294 and it's ppid was 7259 (my shell).