How to find out open file?

Discussion of programming on Linux, including shell scripting, perl, python, c/c++, mono, java. Whatever tickles your fancy.

How to find out open file?

Postby kadnan » Sat Aug 23, 2008 7:20 am

salam after long time!


is there any way to find out whether some "xyz" file is opened by some user? I tried lsof command but it's not doing what I want. I opened a file in gEdit and then try to catch its entry in lsof, i didn't find at all.

Also i tell that I would be accessing file via SAMBA on windows so if Samba provides some facility then please do tell me.
kadnan
Battalion Quarter Master Havaldaar
 
Posts: 208
Joined: Wed Aug 07, 2002 8:00 pm
ICQ: 12940796
Location: Karachi,Pakistan

Postby lambda » Sat Aug 23, 2008 11:43 am

lsof shows you if some process has a file descriptor ("handle") for a file. gedit probably opens the file, reads the contents, and then closes it; that's why it doesn't show up in lsof. if you try another editor, like vi, you'll see that it keeps file descriptor to the file while the editor is running.

i think if you turn up the debugging output for samba, it'll show you the names of files accessed in the log files.

another option is inotify. i don't know if the inotify tools (inotifywatch, etc) can show you the username of someone accessing the file, but you can write an app using the python or ruby inotify api to do what you want.
Watch out for the Manners Taliban!
Isn't it amazing how so many people can type "linuxpakistan.net" into their browsers but not "google.com"?
lambda
Major General
 
Posts: 3452
Joined: Tue May 27, 2003 7:04 pm
Website: http://www.hungry.com/~fn/
Location: Lahore

Postby lambda » Sat Aug 23, 2008 12:41 pm

in fact...

Code: Select all

#!/usr/bin/env python
"""Watch a file or multiple files for certain events."""

import os, os.path
import sys

from pyinotify import ProcessEvent, WatchManager, Notifier, EventsCodes


class PEvent(ProcessEvent):
    """Do something with events."""

    def process_IN_OPEN(self, event):
        """Someone opened a watched file."""

        print 'open', event.path
        os.system('lsof %s 2>/dev/null' % event.path)

    def process_IN_CLOSE_WRITE(self, event):
        """Someone closed a watched file."""

        print 'close', event.path

    def process_IN_CLOSE_NOWRITE(self, event):
        """Someone closed a watched file."""

        print 'close', event.path

    def process_IN_MODIFY(self, event):
        """Someone modified a watched file."""

        print 'modify', event.path
        os.system('lsof %s 2>/dev/null' % event.path)


def usage():
    """Show usage statement."""

    sys.stderr.write('''\
usage: %s filetowatch [file2 file3 ...]
''' % sys.argv[0].split('/')[-1])
    sys.exit(1)


def watch(fnames):
    """Loop forever, watching files."""

    events = EventsCodes.IN_OPEN | EventsCodes.IN_CLOSE_WRITE | \
        EventsCodes.IN_CLOSE_NOWRITE | EventsCodes.IN_MODIFY
    manager = WatchManager()
    notifier = Notifier(manager, PEvent())

    for fname in fnames:
        manager.add_watch(fname, events)
    print 'watching', ' '.join(fnames)

    while True:
        try:
            notifier.process_events()
            if notifier.check_events():
                notifier.read_events()
        except KeyboardInterrupt:
            print 'ending'
            notifier.stop()
            break
        except Exception, err:
            print err


def main(fnames):
    """Main branching logic."""

    if len(fnames) == 0:
        usage()

    # which of the provided filenames actually exist?
    goodfnames = []
    for fname in fnames:
        if os.path.exists(fname):
            goodfnames.append(fname)

    watch(goodfnames)


if __name__ == '__main__':
    main(sys.argv[1:])
Watch out for the Manners Taliban!
Isn't it amazing how so many people can type "linuxpakistan.net" into their browsers but not "google.com"?
lambda
Major General
 
Posts: 3452
Joined: Tue May 27, 2003 7:04 pm
Website: http://www.hungry.com/~fn/
Location: Lahore


Return to “%s” Programming

Who is online

Users browsing this forum: No registered users and 0 guests

cron