Получить md5 файла linux

Подсчитываем md5 (хеш-сумму) в Linux

Проверить MD5 (хеш-сумму) в Linux проще всего именно в терминале. Через какой-либо графический интерфейс необходимо будет сделать больше манипуляций, чем просто скомандовать в терминале Linux следующее:

md5sum /home/pavel/Дистрибутивы/lubuntu-12.04-desktop-i386.iso

Само собой разумеющееся путь до необходимого вам файла, (/home/pavel/Дистрибутивы/lubuntu-12.04-desktop-i386.iso) необходимо прописывать свой, тот который соответствует нужному объекту для подсчета MD5 суммы в Linux.

Чтобы не вводить путь к файлу вручную, его можно скопировать следующим образом. Через файловый менеджер заходим в каталог, где собственно находится тот нужный нам файл. Адресную строку в файловом менеджере необходимо перевести из вида «иконок» в текстовый вид, клавишами , дальше можно скопировать путь либо с помощью мышки через правый клик, либо клавишами . Переходим в терминал и к написанной команде «md5sum» через пробел добавляем наш путь с полным названием файла.

$ md5sum /home/pavel/Дистрибутивы/lubuntu-12.04-desktop-i386.iso 0fc9564b8fde8ff56100c3d7814fa884 /home/pavel/Дистрибутивы/lubuntu-12.04-desktop-i386.iso

Команды в Linux являются стандартном для всех и значит, что команда md5sum подойдет для любого дистрибутива Linux, в котором бы вы не находились. Это и есть одно из достоинств командной строки.

Проверка MD5 (хеш-сумм) требуется после загрузки больших файлов, которые не смогут нормально работать, если какие-либо файлы повредились или каким-то образом изменились. Проверка MD5 сумм в основном применятся к .iso файлам, чаще всего к дистрибутивам. Если .ISO файл поврежден, то его не стоит записывать на USB брелок (флешку), а тем более на оптический диск, дистрибутив Linux при установке будет сообщать об ошибке каких-либо файлов.

После записи дистрибутива Linux на оптический диск нужно проверить целостность, узнать его MD5 сумму

В этой статье мы продолжим углубляться в мир командной строки и сверим MD5 записанного оптического с MD5 суммой исходного файла .ISO с помощью консольной утилиты isoinfo. Для начала мы выудим немного первичной информации о записанном диске командой:

Где /dev/sr0 это DVD-ROM, для уточнения имени вашего примонтированного оптического диска, в том случае если он у вас не один, можно найти по выводу этой команды:

Из имеющейся информации после ввода:

Будет иметься примерно следующее:

CD-ROM is in ISO 9660 format System id: Volume id: Lubuntu 12.04 i386 Volume set id: Publisher id: Data preparer id: XORRISO-1.0.8 2011.04.14.073001, LIBISOBURN-1.0.8, LIBISOFS-1.0.8, LIBBURN-1.0.6 Application id: Copyright File id: Abstract File id: Bibliographic File id: Volume set size is: 1 Volume set sequence number is: 1 Logical block size is: 2048 Volume size is: 352406 El Torito VD version 1 found, boot catalog is in sector 320 Joliet with UCS level 3 found Rock Ridge signatures version 1 found Eltorito validation header: Hid 1 Arch 0 (x86) ID '' Key 55 AA Eltorito defaultboot header: Bootid 88 (bootable) Boot media 0 (No Emulation Boot) Load segment 0 Sys type 0 Nsect 4 Bootoff 52A18 338456

Для нас важны эти строчки:

Logical block size is: 2048 Volume size is: 352406

Далее будем подставлять эти строки в следующую команду, которая нам сообщит MD5 сумму

dd if=/dev/sr0 bs=2048 count=352406 conv=notrunc,noerror | md5sum -b

Обратите внимание на три пункта, которые вы должны подставить свои:

  • /dev/sr0 — путь до оптического диска (если он у вас один, значит этот пункт без изменений)
  • bs= 2048 — у вас своё значение «Logical block size is:»
  • count=352406 — из значения «Volume size is:».
Читайте также:  Linux замена mac адреса

После подсчета вы получите примерно следующее:

352406+0 записей считано 352406+0 записей написано скопировано 721727488 байт (722 MB) 322e76e15cbe9ae4b964f3e6cbe49e37 *- , 55,3223 c, 13,0 MB/c

322e76e15cbe9ae4b964f3e6cbe49e37 — это и есть MD5 сумма диска. Если, она совпадает со значение указанном на сайте, где вы скачивали файл или с исходным файлом на компьютере, то значит, диск записался без ошибок. На практике бывает, что сумма MD5 часто не совпадает с суммой MD5 указанной на сайте из-за ошибок при чтении диска.

Источник

How to Get md5 Hash Of A File

Message-Digest algorithm, commonly known as md5 hash, is a type of cryptographic hash function mainly used to verify the integrity of files. Md5 is a 128-bit message digest produced after running the MD5 function against a file.

Md5 has its flaws and is therefore not a very good choice for certain encryption methods, but it is very well suited for file verification. It works by creating a checksum of a file and comparing the result to the original. That means if there are changes to a file, there is no way it can produce a digest value similar to the original. The value stays constant no matter where generated or how many times as long as the file remains unchanged.

For this guide, we shall look at ways to generate an md5 hash value of a file. That will allow you to verify the integrity of files either from remote locations or on your local machine.

Install md5sum

In Linux and almost major Unix and Unix-Like systems, they come pre-installed with an md5 tool. The most common one is md5sum. By default, you should find it available in your system.

Читайте также:  What is dynamic dns in linux

If you do not have the tool installed, you can use the package manager of your system.

Debian/Ubuntu
On Ubuntu and other Debian based distributions, use apt as:

REHL/CentOS
On REHL and CentOS, use yum as:

Arch/Manjaro
If you are on Manjaro or other arch based distributions, use Pacman using the command:

Fedora
Finally, on Fedora systems, use the dnf command as:

Generate Md5sum of a File

With the tool installed, we can proceed and generate a md5sum for a file. You can use any basic file available in your system. In my example, I am using the /etc/hosts available in Linux systems.

To generate the md5sum of a file, simply use the md5sum command followed by the filename, which you can see in the command below:

The above command should generate a hash value of the file as shown in the output below:

Once the contents of the file change, the md5sum value becomes completely different. For example, add a value to the/etc/hosts file.

Add the following entry to the file (feel free to change to any way you see fit).

If you try to calculate the md5 value of the file with the new contents as:

The hash value is different as shown in the output below:

If you revert the file to its original contents, the md5sum value is similar to the original, allowing you to know when a file has changed.

NOTE: The md5 value will be similar to the original even if the file gets renamed. This is because md5 is calculated based on file contents and not filename.

Verify Online Files

Suppose you want to verify the integrity of a file and ensure it is tamper-proof. To do this, all you need is the original md5 value. In my example, I am using a simple deb package of MySQL from the resource below:

Download the file with wget using the command as:

Once the file has downloaded:

Let us now verify the md5 value using a command:

Читайте также:  Terminal console in linux

If the file has not been modified in any way, you should get a similar value as the original as shown:

Conclusion

This tutorial looked at a simple method to verify the md5 checksum of files and verify their modification state.

Here is a quick exercise for you.

Exercise

Create a simple bash script that checks if a file md5 value has any recorded modification every 5 minutes. If the file has changed, delete the file and shut down the system.

That should be a fun exercise!

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list

Источник

Bash get MD5 of online file

I need to get the MD5 hash of an online file, and then compare it to a file on the local machine. How can I do this in bash?

5 Answers 5

You can use curl to fetch the online file:

curl -sL http://www.your.fi/le | md5sum | cut -d ' ' -f 1 

To compare against another one, store it in a variable and then proceed:

online_md5="$(curl -sL http://www.your.fi/le | md5sum | cut -d ' ' -f 1)" local_md5="$(md5sum "$file" | cut -d ' ' -f 1)" if [ "$online_md5" = "$local_md5" ]; then echo "hurray, they are equal!" fi 

wget can download to standard output with -O- .

 wget http://example.com/some-file.html -O- \ | md5sum \ | cut -f1 -d' ' \ | diff - <(md5sum local-file.html | cut -f1 -d' ') 

md5sum appends the file name after the MD5, you can remove it with cut .

@FinlayRoelofs: it runs diff on the pipe output and output of the command in <(. ) process substitution, i.e. it compares the MD5 sums of the downloaded file and the local file as requested.

 wget -q -O- http://example.com/your_file | md5sum | sed 's:-$:local_file:' | md5sum -c 

Replace http://example.com/your_file with the URL of your online file and local_file with the name of your local file

The output of md5sum is a line containing the checksum and the file name. md5sum -c checks that file name for the checksum. the sed command replaces the - that md5sum uses for stdin with the name of the local file so the md5sum -c at the end verifies that the local file's checksum is the one of the online file.

Источник

Оцените статью
Adblock
detector