Created
May 17, 2019 06:52
-
-
Save gustavorv86/82a08b5b52d34fac63e1aafd61725c5e to your computer and use it in GitHub Desktop.
Search symbolic links into a directory.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
import os | |
import sys | |
PROGNAME = os.path.basename(__file__) | |
EXCLUDE_PATHS = [ | |
"/proc", | |
"/run", | |
"/sys", | |
"/tmp" | |
] | |
def help_and_exit(): | |
print("Usage: {} <search directory> <pattern path>".format(PROGNAME)) | |
print("") | |
exit(1) | |
def find_symlinks(parent_dir, pattern): | |
if not os.path.isdir(parent_dir): | |
print("ERROR: {} is not a directory".format(parent_dir), file=sys.stderr) | |
return | |
for exclude in EXCLUDE_PATHS: | |
if parent_dir.startswith(exclude): | |
return | |
for child_name in os.listdir(parent_dir): | |
child_path = os.path.join(parent_dir, child_name) | |
if os.path.islink(child_path): | |
try: | |
real_path = os.path.join(parent_dir, os.readlink(child_path)) | |
if pattern in real_path: | |
print("{} -> {}".format(child_path, real_path)) | |
except Exception: | |
print("ERROR: {} invalid link".format(child_path), file=sys.stderr) | |
elif os.path.isdir(child_path): | |
find_symlinks(child_path, pattern) | |
def main(argv): | |
if os.getuid() != 0: | |
print("Run as root") | |
exit(0) | |
if len(argv) <= 2: | |
help_and_exit() | |
root_path = argv[1] | |
check_path = argv[2] | |
if os.path.isdir(root_path): | |
find_symlinks(root_path, check_path) | |
else: | |
print("ERROR: {} is not a directory".format(root_path), file=sys.stderr) | |
if __name__ == "__main__": | |
# Use example: ./find_symlinks.py . "" | |
main(sys.argv) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment