Skip to content

Instantly share code, notes, and snippets.

@jlinoff
Last active March 9, 2021 14:47
Show Gist options
  • Save jlinoff/1825507fe2a4e618c4d3 to your computer and use it in GitHub Desktop.
Save jlinoff/1825507fe2a4e618c4d3 to your computer and use it in GitHub Desktop.
Python script that shows how to find all of the open files on a linux system by process /proc/pid/fd.
#!/usr/bin/env python
# License: MIT Open Source
# Copyright (c) 2016 Joe Linoff
'''
This example shows how to find and report all open files on a linux
system by reading /proc/<pid>/fd.
It is similar to the basic functionality provided by the command line
tool lsof but lsof is much faster and provides a lot more
capabilities.
To use it to find all open files do this:
$ sudo find_all_open_files.py
To use it find open files that match a pattern do this:
$ sudo find_all_open_files.py socket: # to find sockets
'''
import os
import re
import sys
def opened_files():
'''
Find all opened files.
'''
try:
for pid in os.listdir('/proc'):
if pid.isdigit():
path = os.path.join('/proc', pid, 'fd')
if os.path.isdir(path):
# /proc/<pid>/fd exists, get the entries.
for entry in os.listdir(path):
link = os.path.join(path, entry)
if os.path.islink(link):
# get the realpath from the link.
real = os.path.realpath(link)
yield pid, real
except OSError:
sys.stderr.write('ERROR: You must run this as a sudo user.\n')
sys.exit(1)
def main():
'''
main
Allow the user to specify regular expressions to match.
If they do not specify regualar expressions, print everything.
'''
regexs = []
for arg in sys.argv[1:]:
regexs.append(re.compile(arg))
for pid, real in opened_files():
print_flag = False if len(regexs) else True
for regex in regexs:
match = regex.search(real)
if match:
print_flag = True
break
if print_flag is True:
print('{:>5} {}'.format(pid, real))
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment