歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux基礎 >> Linux服務器 >> Linux系統遞歸生成目錄中文件的md5的方法

Linux系統遞歸生成目錄中文件的md5的方法

日期:2017/3/2 16:31:08   编辑:Linux服務器

  這篇文章主要介紹了Linux系統遞歸生成目錄中文件的md5的方法,利用PHP腳本實現,需要的朋友可以參考下

  linux下使用md5sum遞歸生成整個目錄的md5

  今天要用md5sum操作目錄,遞歸生成目錄下所有文件的md5值,結果發現它不支持遞歸操作於是寫了個php腳本處理下

  代碼:

  ?

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 <?php $path ='/data/www/bbs/source'; $outfile = 'file.md5'; get_file_md5($path, $outfile); function get_file_md5($path, $outfile) { $path = rtrim($path, '/'); if(function_exists('scandir')) { $files = scandir($path); foreach($files as $v) { if($v != '.' && $v != '..') { $file = $path.'/'.$v; if(is_dir($file)) { get_file_md5($file, $outfile); }else { file_put_contents($outfile, md5_file($file)." ".$file."n", FILE_APPEND); } } } }else { $files = opendir($path); while(($f = readdir($files)) !== false) { if($f == '.' || $f == '..') continue; $file = $path.'/'.$f; if(is_dir($file)) { get_file_md5($file, $outfile); }else { file_put_contents($outfile, md5_file($file)." ".$file."n", FILE_APPEND); } } closedir($files); } }

  注意:生成的md5值和文件之間是兩個空格,否則導致錯誤如下

  代碼如下:

  md5sum: file1.md5: no properly formatted MD5 checksum lines found

  在來個更簡單的,使用linux的find命令一句搞定

  代碼:

  ?

1 find /data/www/bbs/source -type f -print0 | xargs -0 md5sum > file2.md5

  測試

  ?

1 2 md5sum -c file1.md5 md5sum -c file2.md5

  如圖所示

201562992931727.png (1135×790)

  這樣把所有檢測結果輸出到屏幕上來了,如果最後一條顯示這樣的信息 md5sum: WARNING: 2 of 1147 computed checksums did NOT match 則說明在總共1147條中有2條是不符合的

  然後我們可以

  ?

1 md5sum -c file1.md5 | grep FAILED

  就很容易知道是哪些文件的篡改過

Copyright © Linux教程網 All Rights Reserved