Tony
Tony

Reputation: 57

how to know which processes accessed a file?

my os is linux.

I have a file located at /etc,
its full path like /etc/AAA.

any tools or command can tell me the file is accessed by which processes during a period. for example 1:10 AM, process A write /etc/AAA 3:50 AM , process B read /etc/AAA

I need know all processes id who accessed the /et/AAA

Thanks.

Upvotes: 2

Views: 1445

Answers (3)

wojtow
wojtow

Reputation: 975

The linux audit system can help you and will provide detailed information:

Here's some documentation on Redhat's site, but should be adaptable to other linux variants. Most distros have the audit system but may be an optional install. (also see man pages for the commands below)

Assuming the audit subsystem is already running, you can add a rule to watch read access on your example file like this:

auditctl -w /etc/AAA -p r -k mywatch

(-w tells what file to watch, -p tells what activity to watch for [in this case read], and -k is an arbitrary key that can be used to find the records later)

Then you can see the results with the command:

ausearch -k mywatch

or watch the audit.log file (in /var/log/audit on some systems)

Limitation: Note that the filesystem watch (with -p) only logs the opening of a file (with read or write permission), not the time of individual read/write calls. Reading/Writing a large file for example would otherwise generate too many log messages and use up your log file space, so it doesn't do that, it just records the opening of the file. So, in theory a program that's a long running daemon, could open a file for writing at startup (which would be logged) but then not write to it until days later (which wouldn't be logged). Still it should be useful for observing short-lived programs that make a quick change to a file. If you really do want to watch individual calls, there is the -S option to watch syscalls, but use with caution as you can quickly overwhelm your logs if too general.

Upvotes: 5

Aaron Digulla
Aaron Digulla

Reputation: 328574

There is no tool which can do that. To see which process currently has a file open, you can use fuser and lsof.

To get a history of changes, you need to run a process which watches the file system for changes. You can use the inotify service to build this.

Related:

Upvotes: 2

Kokkie
Kokkie

Reputation: 556

stat gives you some of that information;

$ stat test.txt
  File: `test.txt'
  Size: 166             Blocks: 1          IO Block: 65536  regular file
Device: 6a81ccb1h/1786891441d   Inode: 6755399442667785  Links: 1
Access: (0644/-rw-r--r--)  Uid: ( 1000/   PC_01)   Gid: (  513/    None)
Access: 2014-07-16 16:03:18.208462800 +0200
Modify: 2014-07-16 16:03:18.209462900 +0200
Change: 2014-07-16 16:03:18.209462900 +0200
 Birth: 2014-07-16 16:03:18.208462800 +0200

Upvotes: -2

Related Questions