Created
May 17, 2019 06:53
-
-
Save gustavorv86/6c2022362663975b5ba30df6655d3f11 to your computer and use it in GitHub Desktop.
Search broken 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>".format(PROGNAME)) | |
print("") | |
exit(1) | |
def find_broken_symlinks(parent_dir): | |
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 not os.path.exists(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_broken_symlinks(child_path) | |
def main(argv): | |
if os.getuid() != 0: | |
print("Run as root") | |
exit(0) | |
if len(argv) <= 1: | |
help_and_exit() | |
root_path = argv[1] | |
if os.path.isdir(root_path): | |
find_broken_symlinks(root_path) | |
else: | |
print("ERROR: {} is not a directory".format(root_path), file=sys.stderr) | |
if __name__ == "__main__": | |
# Use example: ./find_broken_symlinks.py /usr | |
main(sys.argv) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment