Как найти файл по md5

Given the md5sum of a file, I want to know if anywhere else in the directory tree is another file with the same md5sum (but maybe under a different name). How can I do that in bash?

P.S.: To emphasize, this should work for the entire tree below a given directory, i.e. must work recursively not just in the current directory.

asked Oct 2, 2013 at 5:20

Using find to recursively test all files:

find . -type f -exec 
bash -c 'md5sum "$0" | grep -q 2690d194b68463c5a6dd53d32ba573c7 && echo $0' {} ;

Here, md5sum outputs the MD5 sum and the file name. You need to grep it for the actual MD5 sum as there is no switch to have it just output the sum alone.

You can check the MD5 sum much easier with md5 if you’re on BSD or OS X:

find . -type f -exec 
bash -c '[ "$(md5 -q "$0")" = 2690d194b68463c5a6dd53d32ba573c7 ] && echo $0' {} ;

answered Oct 2, 2013 at 6:01

slhck's user avatar

slhckslhck

221k70 gold badges599 silver badges590 bronze badges

2

The other solutions are good but I want to propose one with fewer spawned processes, which should be significantly faster for many small files, if you have GNU find:

find /path/to/tree -type f -exec md5sum {} + | sed -nre 's/^md5-to-search-for  //p'

or without GNU find:

find /path/to/tree -type f -print0 | xargs -r -0 -- md5sum | sed -nre 's/^md5-to-search-for  //p'

answered Oct 3, 2013 at 8:41

David Foerster's user avatar

Borrowing some of the solution from slhck, I’ve came up with

find . -type f -print0 | while read -r -d '' f;
do
 md5sum "$f" | grep "$1"
done

Where $1 is the first argument. If you want to check for a missing argument start the file with:

if [ -z "$1" ]
  then
    echo "No argument supplied"
    exit
fi

slhck's user avatar

slhck

221k70 gold badges599 silver badges590 bronze badges

answered Oct 2, 2013 at 6:14

tbrixen's user avatar

4

Is there a way I can have a hash value as input when searching for files and a complete list of files and their locations as output?

This could be helpful when trying to pin point file duplicates. I often times find myself in situations where I have a bunch of files that I know I already have stored in some location but I don’t know where. They are essentially duplicates.

For instance, I could have a bunch of files on a portable hard drive, and also hard copies of those files on the internal hard drive of a desktop computer… but I’m not sure of the location! Now if the files are not renamed, I could do a file name search to try to locate the hard copy on the desktop. I could then compare them side by side and in case they are the same I could delete the copy I have on the portable hard drive. But if the files have been renamed on either one of the hard drives this would probably not work (depending on how much the new names differ from the original).

If a file is renamed, but not edited, I could calculate its hash value, e.g. SHA1 value is 74e7432df4a66f246b5214d60b190b67e2f6ce52. I would then like to have this value as input when searching for files and have the operating system search through a given directory or the entire file system for files with this exact SHA1 hash value and output a complete list of locations where these files are stored.

I’m using Windows, but I am generally interested in knowing how something like this could be achieved, regardless of operating system.

asked Dec 24, 2013 at 12:52

Samir's user avatar

4

Linux example:

hash='74e7432df4a66f246b5214d60b190b67e2f6ce52'
find . -type f -exec sh -c '
   sha1sum "$2" | cut -f 1 -d " " | sed "s|^\\||" | grep -Eqi "$1"
' find-sh "$hash" {} ; -print

This code is more complex than you would think it should be because:

  • it is intended to correctly handle filenames with spaces, newlines, backslashes, quotations, special characters etc. (change -print to -print0 to parse them further);
  • it is intended to accept hash(es) as regex (compatible with grep -E i.e. egrep),
    e.g. '^00|00$' will match if the file hash starts or ends with 00; a more practical example is searching by many hashes at once: '74…|a9…|…|…|…' (ellipses for brevity, use full hashes).

You can use other *sum tools with compatible interface (e.g. md5sum).

answered Jul 7, 2017 at 11:19

Kamil Maciorowski's user avatar

Kamil MaciorowskiKamil Maciorowski

67.6k22 gold badges130 silver badges191 bronze badges

4

This is an intriguing question. I have been using a tool called fdupes to accomplish something similar. Fdupes will recursively search through directories and compare every file with every other file. First it compares size, and if the sizes are identical then it creates hashes of the files and compares that, if the hashes are the same then in actually goes through each file byte by byte and compares it.

When if finds all the files that are truly identical you can have it do several things. I have it delete the duplicate and create a hardlink in it’s place (thus saving me HDD space), although you can have it simply output the locations of the duplicate files and not do anything with them. This is the scenario you are asking about.

Some downsides with fdupes are that as far as I know it’s Linux only, and since it compares every file to every other file it takes quite a bit of I/O and time to run. It does not “search” for a file per say, but it would list all the files that have an identical hash.

I would highly recommend it and I set it to run in a cron job every day so that I never have any unnecessary duplicates of my data (it excludes my backups of course).

Fdupes Source Page

answered Dec 24, 2013 at 20:38

tbenz9's user avatar

tbenz9tbenz9

6,9173 gold badges28 silver badges32 bronze badges

If you have PowerShell v.4.0 or higher, you can use the command:

Get-ChildItem _search_location_ -Recurse | Get-FileHash | 
Where-Object hash -eq (Get-FileHash _search_file_).hash | Select path

Where _search_location_ is folder or disk where you want to search for a duplicate and _search_file_ is a file that has a duplicate somewhere. You can put this command in a loop to search for several files or add | Remove-Item at the end of the line to automatically delete duplicates.

Also note that this command is suitable for small search folders only – it will take a lot of time if your search location has thousands of files (like a whole HDD).

Seth's user avatar

Seth

8,9701 gold badge18 silver badges34 bronze badges

answered Dec 20, 2016 at 15:31

Alex K's user avatar

I like to use simple tools that I happen to already have so here is a way to do that with Windows PowerShell (so it obviously only works on windows). It is actually a small edit to Alex K’s answer however the question was how to search using hashes, whereas his answer searched for a copy of a specific file.

Get-ChildItem "_search_location_" -Recurse | Get-FileHash | Where-Object hash -eq _hash_here_ | Select path

Simply replace _search_location_ with what directory you wish to search and replace _hash_here_ with the hash of the file you wish to find.

Seth's user avatar

Seth

8,9701 gold badge18 silver badges34 bronze badges

answered Jul 7, 2017 at 7:22

user746340's user avatar

1

There’s a tool ($) called FileLocator Pro that can search by file hash (SHA-x or MD5).

Excerpt from this page:
http://www.mythicsoft.com/filelocatorpro/help/en/advanced_criteria.htm

Note: If the expression type is set to ‘File Hash’ then the containing
text box can include a comma separated list of hash values or a
pointer to a file containing a list of hash values, e.g.

5A9C9B42A16F5E1985B7B0A019114C7A,675C9B42A16F5E1985B7B0A019114C7A

or,

=c:FileHashTable.txt

The actual algorithms used to calculate the hash, e.g. SHA1, MD5, are
specified in the Options tab.

answered Dec 30, 2013 at 13:42

snowdude's user avatar

snowdudesnowdude

2,86017 silver badges20 bronze badges

Here’s an example for an MD5 algorithm:

Get-ChildItem "_search_location_" -Recurse | Get-FileHash -Algorithm MD5 | Where-Object hash -eq _hash_here_ | Select path

Replace _search_location_ with what directory you wish to search and replace _hash_here_ with the hash of the file you wish to find.

If you want to search for a hash besides the sha256 hash you add -Algorithm _algorithm_ after Get-FileHash where _algorithm_ is the chosen algorithm.

Beware that this requires PowerShell 4.0 and will recalculate every hash for every file for every search!

Seth's user avatar

Seth

8,9701 gold badge18 silver badges34 bronze badges

answered Jul 7, 2017 at 7:39

user746347's user avatar

Voidtools Everything 1.5 search tool has an option to add a column of various hashes, such as CRC-32, CRC-64, MD5, SHA-1, SHA-256 for each file.

enter image description here

You can then search for a particular hash as well, for example md5:71E..
enter image description here

answered Apr 22 at 19:53

Rudolph's user avatar

RudolphRudolph

2121 gold badge5 silver badges20 bronze badges

. алгоритмы гашиш кому удается создать буквенно-цифровую строку обычно фиксированной длины из текста, пароля или файла. В этой цепочке хранится сводка всей информации о файле или элементе ввода, и ее цель состоит в том, чтобы пароль был нечитаемым или файл был зашифрован по соображениям безопасности. Тогда мы покажем как мы можем искать файлы по хешу в Windows .

Для этого нам придется использовать инструмент, который не позволяет именно этого, поиск файлов путем хеширования в Windows. Умный поиск файлов et программное обеспечение, хотя и бесплатное, но представляет собой поисковую систему, которая предлагает возможность простого поиска файлов с помощью хеширования в Windows.

Это приложение использует несколько критериев для поиска файлов по хешу, одним из которых является то, что оно позволяет искать файлы по хеш-значению. Он совместим с MD5, SHA1, SHA256, SHA512 или TIGER192 , среди прочего, и для этого вам просто нужно указать значение хеш-функции в поле поиска и путь для начала.

Smart File Finder покажет нам файл, который соответствует критериям, установленным в поиске, и покажет нам имя файла и путь, по которому он находится. Кроме того, можно указать приложению исключить определенные файлы или папки из результатов поиска, использовать известные подстановочные знаки или оставить скрытые файлы и каталоги.

Другой вариант – использовать сценарий PowerShell. который можно найти на Github и который откроет окно с формой для поиска файлов путем хеширования в Windows. В этой форме мы должны указать Хеш MD5 и маска, в которой мы хотим искать . Результат даст нам имя файла, которое соответствует заданному хешу и пути.

Чтобы использовать этот метод, первое, что нужно сделать, это открыть PowerShell, зайдите в Github и скопируйте код скрипта , затем скопируйте его в интерфейс Power Shell. Теперь, чтобы запустить скрипт, просто нажмите кнопку воспроизведения, и появится окно, в котором мы можем указать хеш MD5 и путь, по которому мы хотим искать. Нажмите «Поиск», и процесс поиска начнется автоматически. Когда это будет сделано, мы сможем увидеть имя и путь к искомому файлу, который соответствует заданному хешу.

I have a file x1 in one directory (d1) and I’m not sure if the same
file is already copied (x2) in another directory (d2) (but automatically
renamed by application).

Can I check if hash of file x1 from directory d1 is equal to hash of some file x2 existing in directory d2?

asked Jan 23, 2017 at 10:24

xralf's user avatar

This is a good approach, but the search will be a lot faster if you only calculate hashes of files that have the right size. Using GNU/BusyBox utilities:

wanted_size=$(stat -c %s d1/x1)
wanted_hash=$(sha256sum <d1/x1)
find d2 -type f -size "${wanted_size}c" -execdir sh -c 'test "$(sha256sum <"$0")" = "$1"' {} "$wanted_hash" ; -print

answered Jan 25, 2017 at 2:06

Gilles 'SO- stop being evil''s user avatar

To find a file with a known MD5 digest in a directory (using bash or ksh93):

x1digest="$( md5sum d1/x1 | cut -d ' ' -f 1 )"

for x2 in d2/*; do
    if [[ ! -f "$fpath" ]]; then
      continue
    fi

    x2digest="$( md5sum "$fpath" | cut -d ' ' -f 1 )"

    if [[ "$x2digest" == "$x1digest" ]]; then
      printf '"%s" has the same hash as d1/x1n' "$fpath"
    fi
done

On BSD systems, md5sum filename | cut -d ' ' -f 1 can be replaced by md5 -q filename.

answered Jan 23, 2017 at 10:28

Kusalananda's user avatar

KusalanandaKusalananda

315k36 gold badges622 silver badges921 bronze badges

Есть ли способ получить хеш-значение в качестве ввода при поиске файлов и полный список файлов и их расположения в качестве вывода?

Это может быть полезно при попытке определить дубликаты файлов. Я часто оказываюсь в ситуациях, когда у меня есть куча файлов, которые, как я знаю, уже были сохранены в каком-то месте, но я не знаю, где. Они по сути дубликаты.

Например, у меня может быть куча файлов на переносном жестком диске, а также бумажные копии этих файлов на внутреннем жестком диске настольного компьютера … но я не уверен в их местонахождении! Теперь, если файлы не переименованы, я могу выполнить поиск по имени файла, чтобы попытаться найти печатную копию на рабочем столе. Затем я могу сравнить их рядом, и в случае, если они совпадают, я могу удалить имеющуюся копию на переносном жестком диске. Но если файлы были переименованы на одном из жестких дисков, это, вероятно, не сработает (в зависимости от того, насколько новые имена отличаются от оригинальных).

Если файл переименован, но не отредактирован, я мог бы вычислить его хеш-значение, например, значение SHA1 равно 74e7432df4a66f246b5214d60b190b67e2f6ce52 . Затем я хотел бы использовать это значение в качестве входных данных при поиске файлов, чтобы операционная система выполняла поиск по заданному каталогу или по всей файловой системе для файлов с этим точным значением хеш-функции SHA1 и выводила полный список мест, где эти файлы хранятся.

Я использую Windows, но мне, как правило, интересно знать, как можно добиться чего-то подобного, независимо от операционной системы.

Добавить комментарий