Linux : 주어진 폴더 및 콘텐츠에 대해 단일 해시를 계산합니까?
확실히 이것을 쉽게 할 수있는 방법이있을 것입니다!
나는 리눅스 명령 줄과 같은 애플 리케이션 해봤 sha1sum하고 md5sum있지만 개별 파일 및 출력 해시 값 목록, 각 파일에 대해 하나의 해시를 계산 할 수있을 것 같다.
파일 이름뿐만 아니라 폴더의 전체 내용에 대해 단일 해시를 생성해야합니다.
나는 다음과 같은 것을하고 싶다.
sha1sum /folder/of/stuff > singlehashvalue
편집 : 명확히하기 위해 내 파일은 디렉토리 트리의 여러 수준에 있으며 모두 동일한 루트 폴더에 있지 않습니다.
한 가지 가능한 방법은 다음과 같습니다.
sha1sum 경로 / 대상 / 폴더 / * | sha1sum
전체 디렉토리 트리가 있으면 find 및 xargs를 사용하는 것이 좋습니다. 가능한 명령 중 하나는
경로 / 대상 / 폴더 찾기 -type f -print0 | 정렬 -z | xargs -0 sha1sum | sha1sum
마지막으로 권한과 빈 디렉터리도 고려해야하는 경우 :
(find path/to/folder -type f -print0 | sort -z | xargs -0 sha1sum;
find path/to/folder \( -type f -o -type d \) -print0 | sort -z | \
xargs -0 stat -c '%n %a') \
| sha1sum
인수 stat는 파일 이름과 그 뒤에 8 진수 권한을 인쇄하도록합니다. 두 개의 발견은 차례로 실행되어 디스크 IO의 양을 두 배로 늘리고 첫 번째는 모든 파일 이름을 찾고 내용을 체크섬하고 두 번째는 모든 파일 및 디렉토리 이름을 찾고 이름과 모드를 인쇄합니다. "파일 이름 및 체크섬"목록과 "권한이있는 이름 및 디렉토리"목록이 더 작은 체크섬에 대해 체크섬됩니다.
aide 와 같은 파일 시스템 침입 탐지 도구를 사용하십시오 .
디렉토리의 타르 볼을 해시합니다.
tar cvf - /path/to/folder | sha1sumvatine의 oneliner 와 같이 직접 코딩하십시오 .
find /path/to/folder -type f -print0 | sort -z | xargs -0 sha1sum | sha1sum
넌 할 수있어 tar -c /path/to/folder | sha1sum
폴더의 내용이 변경되었는지 확인하려면 다음을 권장합니다.
ls -alR --full-time /folder/of/stuff | sha1sum
폴더, 하위 폴더, 파일, 타임 스탬프, 크기 및 권한이 포함 된 ls 출력의 해시 만 제공합니다. 무언가 변경되었는지 확인하는 데 필요한 거의 모든 것.
이 명령은 각 파일에 대해 해시를 생성하지 않지만 find를 사용하는 것보다 빠르다는 점에 유의하십시오.
파일 내용을 해시하고 파일 이름을 무시하려면 다음을 사용할 수 있습니다.
cat $FILES | md5sum
해시를 계산할 때 파일이 동일한 순서로 있는지 확인하십시오.
cat $(echo $FILES | sort) | md5sum
그러나 파일 목록에는 디렉토리가있을 수 없습니다.
이를위한 파이썬 스크립트가 있습니다 :
http://code.activestate.com/recipes/576973-getting-the-sha-1-or-md5-hash-of-a-directory/
알파벳 순서를 변경하지 않고 파일 이름을 변경하면 해시 스크립트가이를 감지하지 못합니다. 그러나 파일의 순서 나 파일의 내용을 변경하면 스크립트를 실행하면 이전과 다른 해시가 제공됩니다.
강력하고 깨끗한 접근 방식
- 먼저 , 사용 가능한 메모리를 잡아 먹지 마십시오 ! 전체 파일을 공급하는 대신 청크로 파일을 해시하십시오.
- 다양한 요구 / 목적에 대한 다양한 접근 방식 (아래 모두 또는 적용되는 항목 선택) :
- 디렉토리 트리에있는 모든 항목의 항목 이름 만 해시합니다.
- 모든 항목의 파일 내용을 해시합니다 (메타를 그대로두고 inode 번호, ctime, atime, mtime, 크기 등).
- 심볼릭 링크의 경우 내용은 참조 이름입니다. 해시하거나 건너 뛰도록 선택
- 항목의 내용을 해싱하는 동안 심볼릭 링크를 따르거나 따르지 않을 (확인 된 이름)
- 디렉토리 인 경우 내용은 디렉토리 항목 일뿐입니다. 재귀 적으로 순회하는 동안 그들은 결국 해시 될 것이지만이 디렉토리에 태그를 지정하기 위해 해당 수준의 디렉토리 항목 이름을 해시해야합니까? 콘텐츠를 해시하기 위해 깊이 탐색하지 않고도 변경 사항을 빠르게 식별하기 위해 해시가 필요한 사용 사례에 유용합니다. 예를 들어 파일의 이름이 변경되지만 나머지 내용은 동일하게 유지되고 모두 상당히 큰 파일입니다.
- 대용량 파일을 잘 처리하십시오 (다시 RAM에 유의하십시오).
- 매우 깊은 디렉토리 트리 처리 (열린 파일 설명자에 유의)
- 비표준 파일 이름 처리
- 소켓, 파이프 / FIFO, 블록 장치, 문자 장치 인 파일을 처리하는 방법은 무엇입니까? 그것들도 해시해야합니까?
- 통과하는 동안 항목의 액세스 시간을 업데이트하지 마십시오. 이는 특정 사용 사례에 대해 부작용과 역효과 (직관적?)가 될 수 있기 때문입니다.
이것이 제가 머리 위에있는 것입니다.이 작업에 시간을 할애 한 사람은 다른 문제와 코너 케이스를 잡았을 것입니다.
다음 은 대부분의 경우를 처리하는 매우 가벼운 메모리 도구입니다 . 가장자리가 약간 거칠지 만 상당히 도움이되었습니다.
예 사용 및 출력 dtreetrawl.
Usage: dtreetrawl [OPTION...] "/trawl/me" [path2,...] Help Options: -h, --help Show help options Application Options: -t, --terse Produce a terse output; parsable. -j, --json Output as JSON -d, --delim=: Character or string delimiter/separator for terse output(default ':') -l, --max-level=N Do not traverse tree beyond N level(s) --hash Enable hashing(default is MD5). -c, --checksum=md5 Valid hashing algorithms: md5, sha1, sha256, sha512. -R, --only-root-hash Output only the root hash. Blank line if --hash is not set -N, --no-name-hash Exclude path name while calculating the root checksum -F, --no-content-hash Do not hash the contents of the file -s, --hash-symlink Include symbolic links' referent name while calculating the root checksum -e, --hash-dirent Include hash of directory entries while calculating root checksum
인간 친화적 출력의 일부 :
... ... //clipped ... /home/lab/linux-4.14-rc8/CREDITS Base name : CREDITS Level : 1 Type : regular file Referent name : File size : 98443 bytes I-node number : 290850 No. directory entries : 0 Permission (octal) : 0644 Link count : 1 Ownership : UID=0, GID=0 Preferred I/O block size : 4096 bytes Blocks allocated : 200 Last status change : Tue, 21 Nov 17 21:28:18 +0530 Last file access : Thu, 28 Dec 17 00:53:27 +0530 Last file modification : Tue, 21 Nov 17 21:28:18 +0530 Hash : 9f0312d130016d103aa5fc9d16a2437e Stats for /home/lab/linux-4.14-rc8: Elapsed time : 1.305767 s Start time : Sun, 07 Jan 18 03:42:39 +0530 Root hash : 434e93111ad6f9335bb4954bc8f4eca4 Hash type : md5 Depth : 8 Total, size : 66850916 bytes entries : 12484 directories : 763 regular files : 11715 symlinks : 6 block devices : 0 char devices : 0 sockets : 0 FIFOs/pipes : 0
나는 파이프를 통해 개별 파일에 대한 결과 것 sort으로 (파일의 단순한 재 배열을 방지하기 위해 해시 변경) md5sum또는 sha1sum당신이 선택 중을.
이를 달성하기위한 또 다른 도구 :
http://md5deep.sourceforge.net/
소리 그대로 : md5sum과 비슷하지만 재귀 적이며 다른 기능도 있습니다.
이 작업을 수행하기 위해 Groovy 스크립트를 작성했습니다.
import java.security.MessageDigest
public static String generateDigest(File file, String digest, int paddedLength){
MessageDigest md = MessageDigest.getInstance(digest)
md.reset()
def files = []
def directories = []
if(file.isDirectory()){
file.eachFileRecurse(){sf ->
if(sf.isFile()){
files.add(sf)
}
else{
directories.add(file.toURI().relativize(sf.toURI()).toString())
}
}
}
else if(file.isFile()){
files.add(file)
}
files.sort({a, b -> return a.getAbsolutePath() <=> b.getAbsolutePath()})
directories.sort()
files.each(){f ->
println file.toURI().relativize(f.toURI()).toString()
f.withInputStream(){is ->
byte[] buffer = new byte[8192]
int read = 0
while((read = is.read(buffer)) > 0){
md.update(buffer, 0, read)
}
}
}
directories.each(){d ->
println d
md.update(d.getBytes())
}
byte[] digestBytes = md.digest()
BigInteger bigInt = new BigInteger(1, digestBytes)
return bigInt.toString(16).padLeft(paddedLength, '0')
}
println "\n${generateDigest(new File(args[0]), 'SHA-256', 64)}"
각 파일 인쇄를 방지하고, 메시지 다이제스트를 변경하고, 디렉토리 해싱을 꺼내는 등의 용도를 사용자 정의 할 수 있습니다. NIST 테스트 데이터에 대해 테스트했으며 예상대로 작동합니다. http://www.nsrl.nist.gov/testdata/
gary-macbook:Scripts garypaduana$ groovy dirHash.groovy /Users/garypaduana/.config
.DS_Store
configstore/bower-github.yml
configstore/insight-bower.json
configstore/update-notifier-bower.json
filezilla/filezilla.xml
filezilla/layout.xml
filezilla/lockfile
filezilla/queue.sqlite3
filezilla/recentservers.xml
filezilla/sitemanager.xml
gtk-2.0/gtkfilechooser.ini
a/
configstore/
filezilla/
gtk-2.0/
lftp/
menus/
menus/applications-merged/
79de5e583734ca40ff651a3d9a54d106b52e94f1f8c2cd7133ca3bbddc0c6758
두 단계로 만들어보십시오.
- 폴더의 모든 파일에 대해 해시가있는 파일 만들기
- 이 파일을 해시
이렇게 :
# for FILE in `find /folder/of/stuff -type f | sort`; do sha1sum $FILE >> hashes; done
# sha1sum hashes
또는 한 번에 모두 수행하십시오.
# cat `find /folder/of/stuff -type f | sort` | sha1sum
sha1sum해시 값 목록을 생성 한 다음 sha1sum해당 목록을 다시 생성 할 수 있습니다. 정확히 무엇을 달성 하려는지에 따라 다릅니다.
파일 변경을 위해 전체 디렉토리를 확인해야했습니다.
그러나 제외, 타임 스탬프, 디렉토리 소유권.
목표는 파일이 동일한 경우 어디서나 동일한 합계를 얻는 것입니다.
Including hosted into other machines, regardless anything but the files, or a change into them.
md5sum * | md5sum | cut -d' ' -f1
It generate a list of hash by file, then concatenate those hashes into one.
This is way faster than the tar method.
For a stronger privacy in our hashes, we can use sha512sum on the same recipe.
sha512sum * | sha512sum | cut -d' ' -f1
The hashes are also identicals anywhere using sha512sum but there is no known way to reverse it.
Here's a simple, short variant in Python 3 that works fine for small-sized files (e.g. a source tree or something, where every file individually can fit into RAM easily), ignoring empty directories, based on the ideas from the other solutions:
import os, hashlib
def hash_for_directory(path, hashfunc=hashlib.sha1):
filenames = sorted(os.path.join(dp, fn) for dp, _, fns in os.walk(path) for fn in fns)
index = '\n'.join('{}={}'.format(os.path.relpath(fn, path), hashfunc(open(fn, 'rb').read()).hexdigest()) for fn in filenames)
return hashfunc(index.encode('utf-8')).hexdigest()
It works like this:
- Find all files in the directory recursively and sort them by name
- Calculate the hash (default: SHA-1) of every file (reads whole file into memory)
- Make a textual index with "filename=hash" lines
- Encode that index back into a UTF-8 byte string and hash that
You can pass in a different hash function as second parameter if SHA-1 is not your cup of tea.
If this is a git repo and you want to ignore any files in .gitignore, you might want to use this:
git ls-files <your_directory> | xargs sha256sum | cut -d" " -f1 | sha256sum | cut -d" " -f1
This is working well for me.
참고URL : https://stackoverflow.com/questions/545387/linux-compute-a-single-hash-for-a-given-folder-contents
'Programing' 카테고리의 다른 글
| 여러 외래 키와 Rails 연관 (0) | 2020.10.24 |
|---|---|
| Postgresql을 다시 시작하는 방법 (0) | 2020.10.24 |
| 암시 적 인터페이스와 명시 적 인터페이스 구현 (0) | 2020.10.24 |
| 두 텍스트 파일에서 줄을 인터리브하는 방법 (0) | 2020.10.24 |
| mysql 기간 및 가져 오기 시간 (0) | 2020.10.24 |