简体   繁体   中英

How to identify a hardlink using python?

I would like to know if it is possible identify whether a file (or link) is a hardlink or not, on Linux. For instance, If I created:

dd if=/dev/urandom bs=1024 count=10000 of=file_10MB conv=notrunc
ln file_10MB file_10MB_link1

I would like to create a check function, that could be used like this:

if is_hardlink("file_10MB_link1"):
    pass

How can I use Python to check if a file is a hardlink ?

I believe you're looking for "files which have a link count greater than 1"

for that you can use:

def more_than_one_link(filename):
    os.stat(filename).st_nlink > 1

No, it's not possible. There's nothing that distinguishes the original file from the hard link. They're just two names that refer to the same inode number, which represents the file contents.

You can use the code in Anthony Sottile's answer to tell if the file has multiple links to it, but you can't tell which is the original.

The answer is that that it depends on the filesystem and (exact) OS you are using. For example, if you are using NTFS (although unlikely in a native Linux context) it allows for a wide range of NTFS specific features including hardlinks and junctions . So while in Windows they use link numbers for hardlinks, Linux OS use inodes.

You would need specific kernel drivers or a forensic OS to be able to read all those, as normal Linux are using only inodes , and would need to be counted and time-stamp analyzed to decided what is the original file vs. a later created hardlink(s).

As python can create both hardlinks and softlinks via:

os.link()    # Create a hard link
os.symlink() # Create a symbolic link

(TL;DR the long docs above) there should be a way for you to check the link type, although it may require quite a bit of disc processing (searching and comparing).

For the exact detection check the built-in os functions, explained in this answer .
[islink(), parse_reparse_buffer(), readlink()]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM