4

How do I see the list of files open (lsof) in a specific directory and by other users?

I can do lsof +D /path, but that only shows current user's files.

Any way to see if other users have opened files in a directory?

U880D
  • 597
  • 7
  • 17

3 Answers3

4

Since I had the similar question recently I wanted to share my findings here too. Also it is assumed that the user is root and as mentioned in the other answers.

List open files within a specific directory

lsof +D /var/log/

will show files opened from all users.

Specifying the user

lsof -u ${USER} +D /var/log/

will show all files from the user OR within the specific directory (... AND independet from the user).

This is because of and as stated in man lsof:

Since they represent exclusions, they are applied without ORing or ANDing and take effect before any other selection criteria are applied.

The -a option may be used to AND the selections. For example, specifying -a, -U, and -ufoo produces a listing of only UNIX socket files that belong to processes owned by user ``foo''.

To list open files from the user AND within a specific directory only

lsof -u ${USER} -a +D /var/log/ 

It is then possible to list open files which are NOT the user AND within a specific directory.

lsof -u ^${USER} -a +D /var/log/ 

This approach is also working good for network connections. I.e if interested in all TCP OR UDP connections which are opened by NOT under root running processes

lsof -u ^root -P -i TCP -i UDP

To address the issue with the non root user, sudo and sudoers it will be necessary to Identify the sudo calling user.

List all open files within a specific directory AND opened from the user

sudo lsof -u $(who | cut -d " " -f 1) -a +D /usr/lib/

otherwise it would show opened files OR within the directory AND indepent from the user.

List all open files within a specific directory NOT opened by the mentioned user

sudo lsof -u ^$(who | cut -d " " -f 1) +D /usr/lib/
U880D
  • 597
  • 7
  • 17
3

You can't unless you are performing this as root.

If you wanted, you can setup an sudo alias for lsof, but it would either be very generic.

I.e. this user can see the whole lsof output or very specific since this user can only see this other user's lsof -u user output.

U880D
  • 597
  • 7
  • 17
Philip Reynolds
  • 9,751
  • 1
  • 32
  • 33
2

i assume you run as root / can sudo as root lsof:

lsof -u www-data
pQd
  • 29,561
  • 5
  • 64
  • 106
  • 1
    Nope, the user that's running lsof isnt (cannot be) root. However he does have rwx access to the dir and files the other user is writing to –  Nov 23 '09 at 09:03
  • 1
    @Ash - so user cannot. you can suid lsof or allow user to run it as root via sudo. but those are not good ideas. user needs to have access to /proc/processnumber to check current working dir for processes run by others. just read access to his home folder is not enough. – pQd Nov 23 '09 at 11:44