Reputation: 3479
I need to find which proccess, user or pc has a certain file open. I can do it manually through the utilities that come with the win server but I would like to script this since I am dealing with hundreds of files.
Any ideas, suggestions please?
Basically a list of the information below:
Upvotes: 1
Views: 499
Reputation: 44354
To get this info requires some undocumented Win32 APIs. You could call something like handle.exe
from sysinternals which uses them, but I suggest you use the psutil
module, available from PyPi. Here is some example code (Py3) I happen to have which lists all the files in use, you should be able to modify that:
import psutil
for proc in psutil.process_iter():
try:
flist = proc.get_open_files()
if flist:
print(proc.pid,proc.name)
for nt in flist:
print("\t",nt.path)
except psutil.NoSuchProcess as err:
print("****",err)
Note that there is always a chance of a race condition with these kind of queries - you do not know at what point a process opens or closes a file, or even starts and finishes.
PS: if you are on Python 3, I had some problems installing psutil, but usinging the 2to3 conversion utility on the setup.py fixed the issues.
Upvotes: 2