-
-
Save James-Firth/8389517 to your computer and use it in GitHub Desktop.
Forked from https://gist.github.com/hollobon/7579947/ This script recursively checks a directory's files for hardlinks. If there's no other links to a file the name is printed. TODO: Add flags to only print filenames above or below a link count threshold. Add a flag to be recursive.
This file contains 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
import os | |
import sys | |
import tempfile | |
import win32file | |
from glob import glob | |
def get_link_count(filename): | |
if os.path.isdir(filename): | |
dwFlagsAndAttributes = win32file.FILE_FLAG_BACKUP_SEMANTICS | |
else: | |
dwFlagsAndAttributes = 0 | |
handle = win32file.CreateFile(filename, | |
win32file.GENERIC_READ, | |
win32file.FILE_SHARE_READ, | |
None, | |
win32file.OPEN_EXISTING, | |
dwFlagsAndAttributes, | |
None) | |
(attributes, created_at, accessed_at, written_at, volume, file_hi, file_lo, | |
n_links, index_hi, index_lo) = win32file.GetFileInformationByHandle(handle) | |
return n_links | |
def check_links_in_dir(dirname): | |
print(os.linesep+"Checking for hardlinks in: '"+dirname+"'") | |
if os.path.isdir(dirname): | |
print("The following files have no hardlinks elsewhere:") | |
for fname in os.listdir(dirname): | |
fpath = os.path.join(dirname,fname) | |
if os.path.isfile(fpath): | |
hardcount = get_link_count(fpath) | |
if hardcount == 1: | |
print(fname) | |
elif os.path.isdir(fpath): | |
check_links_in_dir(fpath) | |
else: | |
print("'"+fpath+"' is not a file!") | |
else: | |
print("ERROR. Not a directory.") | |
def main(): | |
temp_dirname = glob(sys.argv[1]) | |
if len(temp_dirname) >= 1: | |
dirname = temp_dirname[0] | |
if os.path.isdir(dirname): | |
check_links_in_dir(dirname) | |
else: | |
print("Error, improper pathname.") | |
if __name__ == "__main__": | |
sys.exit(main()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment