如何使用python替换带有硬链接的重复文件?

时间:2013-06-21 23:35:07

标签: python linux duplicates nas hardlink

我是一名摄影师并做了很多备份。多年来,我发现自己有很多硬盘。现在我买了一台NAS并使用rsync在一个3TB raid 1上复制了我所有的照片。根据我的脚本,这些文件的1TB是重复的。这是因为在删除笔记本电脑上的文件并且非常混乱之前进行多次备份。我确实备份了旧硬盘上的所有文件,但如果我的脚本搞砸了,那将会很痛苦。你能看看我的重复查找器脚本并告诉我你是否认为我可以运行它?我在一个测试文件夹上试了一下它似乎没问题,但我不想把它搞砸在NAS上。

该脚本在三个文件中有三个步骤。在第一部分中,我找到了所有图像和元数据文件,并将它们放入搁置数据库(datenbank)中,其大小为关键。

import os
import shelve

datenbank = shelve.open(os.path.join(os.path.dirname(__file__),"shelve_step1"), flag='c', protocol=None, writeback=False)

#path_to_search = os.path.join(os.path.dirname(__file__),"test")
path_to_search = "/volume1/backup_2tb_wd/"
file_exts = ["xmp", "jpg", "JPG", "XMP", "cr2", "CR2", "PNG", "png", "tiff", "TIFF"]
walker = os.walk(path_to_search)

counter = 0

for dirpath, dirnames, filenames in walker:
  if filenames:
    for filename in filenames:
      counter += 1
      print str(counter)
      for file_ext in file_exts:
        if file_ext in filename:
          filepath = os.path.join(dirpath, filename)
          filesize = str(os.path.getsize(filepath))
          if not filesize in datenbank:
            datenbank[filesize] = []
          tmp = datenbank[filesize]
          if filepath not in tmp:
            tmp.append(filepath)
            datenbank[filesize] = tmp

datenbank.sync()
print "done"
datenbank.close()

第二部分。现在我删除列表中只有一个文件的所有文件大小,并创建另一个搁置数据库,其中md5哈希为密钥,文件列表为值。

import os
import shelve
import hashlib

datenbank = shelve.open(os.path.join(os.path.dirname(__file__),"shelve_step1"), flag='c', protocol=None, writeback=False)

datenbank_step2 = shelve.open(os.path.join(os.path.dirname(__file__),"shelve_step2"), flag='c', protocol=None, writeback=False)

counter = 0
space = 0

def md5Checksum(filePath):
    with open(filePath, 'rb') as fh:
        m = hashlib.md5()
        while True:
            data = fh.read(8192)
            if not data:
                break
            m.update(data)
        return m.hexdigest()


for filesize in datenbank:
  filepaths = datenbank[filesize]
  filepath_count = len(filepaths)
  if filepath_count > 1:
    counter += filepath_count -1
    space += (filepath_count -1) * int(filesize)
    for filepath in filepaths:
      print counter
      checksum = md5Checksum(filepath)
      if checksum not in datenbank_step2:
        datenbank_step2[checksum] = []
      temp = datenbank_step2[checksum]
      if filepath not in temp:
        temp.append(filepath)
        datenbank_step2[checksum] = temp

print counter
print str(space)

datenbank_step2.sync()
datenbank_step2.close()
print "done"

最后是最危险的部分。对于evrey md5键,我检索文件列表并执行额外的sha1。如果匹配,我删除该列表中的每个文件,除了第一个文件,并创建一个硬链接来替换已删除的文件。

import os
import shelve
import hashlib

datenbank = shelve.open(os.path.join(os.path.dirname(__file__),"shelve_step2"), flag='c', protocol=None, writeback=False)

def sha1Checksum(filePath):
    with open(filePath, 'rb') as fh:
        m = hashlib.sha1()
        while True:
            data = fh.read(8192)
            if not data:
                break
            m.update(data)
        return m.hexdigest()

for hashvalue in datenbank:
  switch = True
  for path in datenbank[hashvalue]:
    if switch:
      original = path
      original_checksum = sha1Checksum(path)
      switch = False
    else:
      if sha1Checksum(path) == original_checksum:
        os.unlink(path)
        os.link(original, path)
        print "delete: ", path
print "done"
你怎么看? 非常感谢你。

*如果这有点重要:它是一个synology 713+并且有一个ext3或ext4文件系统。

4 个答案:

答案 0 :(得分:1)

为什么不比较文件字节的字节而不是第二个校验和?十分之一的两个校验和可能会意外匹配,但直接比较不应该失败。它不应该慢,甚至可能更快。当有两个以上的文件并且你必须为彼此读取原始文件时,它可能会更慢。如果你真的想要通过一次比较所有文件的块来解决这个问题。

编辑:

我不认为它需要更多代码,只是不同。这样的循环体:

data1 = fh1.read(8192)
data2 = fh2.read(8192)
if data1 != data2: return False

答案 1 :(得分:1)

这看起来不错,经过消毒(使其与python 3.4一起使用)后,我在NAS上运行了这个。虽然我在备份之间没有修改过的文件有硬链接,但移动的文件正在被复制。这恢复了我丢失的磁盘空间。

一个小小的挑剔是已经硬链接的文件被删除并重新链接。这无论如何都不会影响最终结果。

确实稍微改变了第三个文件(“3.py”):

if sha1Checksum(path) == original_checksum:
     tmp_filename = path + ".deleteme"
     os.rename(path, tmp_filename)
     os.link(original, path)
     os.unlink(tmp_filename)
     print("Deleted {} ".format(path))

这可确保在出现电源故障或其他类似错误的情况下,不会丢失任何文件,但会留下尾随的“deleteme”。恢复脚本应该非常简单。

答案 2 :(得分:0)

如何创建硬链接。

在linux中你做

sudo ln sourcefile linkfile

有时这可能会失败(对我而言,它有时会失败)。你的python脚本也需要在sudo模式下运行。

所以我使用符号链接:

ln -s sourcefile linkfile

我可以使用os.path.islink

检查它们

你可以在Python中调用这样的命令:

os.system("ln -s sourcefile linkfile")

或使用subprocess

这样的人
import subprocess
subprocess.call(["ln", "-s", sourcefile, linkfile], shell = True)

查看execution from command linehard vs. soft links

当它有效时,你可以发布你的整个代码吗?我也想用它。

答案 3 :(得分:0)

注意:如果您没有使用Python,那么现有的工具可以帮助您完成繁重的工作:

https://unix.stackexchange.com/questions/3037/is-there-an-easy-way-to-replace-duplicate-files-with-hardlinks