Linux: 특정 폴더 및 컨텐츠에 대해 단일 해시를 계산합니까?
분명히 쉽게 할 수 있는 방법이 있을 거야!
을 사용해 보았습니다sha1sum ★★★★★★★★★★★★★★★★★」md5sum그러나 개별 파일의 해시를 계산하고 각 파일에 대해 하나씩 해시 값 목록을 출력할 수 있을 뿐입니다.
파일 이름뿐만 아니라 폴더의 전체 내용에 대해 단일 해시를 생성해야 합니다.
뭔가 하고 싶은 게 있는데
sha1sum /folder/of/stuff > singlehashvalue
편집: 명확하게 말하면, 내 파일은 디렉토리 트리의 여러 레벨에 있지만, 모두 같은 루트 폴더에 있는 것은 아닙니다.
생각할 수 있는 방법 중 하나는 다음과 같습니다.
sha1sum path/to/folder/* | sha1sum
디렉토리 트리 전체가 있는 경우는, find 와 xargs 를 사용하는 것이 좋습니다.가능한 명령어 중 하나는
find path / to / folder - type f - print0 | sort - 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진수 권한이 인쇄됩니다.2개의 검색은 차례로 실행되어 디스크 IO의 양이 2배가 됩니다.첫 번째 검색은 모든 파일명을 검색하여 내용을 체크섬합니다.두 번째 검색은 모든 파일명과 디렉토리명, 인쇄명과 모드를 검색합니다.그런 다음 "파일 이름과 체크섬" 목록 뒤에 "사용 권한이 있는 이름과 디렉토리"가 체크섬을 더 작게 만듭니다.
보조 도구와 같은 파일 시스템 침입 탐지 도구를 사용합니다.
디렉토리의 tar ball을 해시합니다.
tar cvf - /path/to/folder | sha1sum바틴의 오닐라이너와 같은 것을 직접 코딩하십시오.
find /path/to/folder -type f -print0 | sort -z | xargs -0 sha1sum | sha1sum
폴더 내의 무언가가 변경되었는지 확인하고 싶다면 다음 중 하나를 권장합니다.
ls -alR --full-time /folder/of/stuff | sha1sum
폴더, 서브폴더, 파일, 타임스탬프, 크기 및 권한을 포함하는 LS 출력의 해시만 제공합니다.뭔가 바뀌었는지 판단하기 위해 필요한 거의 모든 것.
이 명령어는 각 파일에 대해 해시를 생성하지 않으므로 find를 사용하는 것보다 더 빠를 수 있습니다.
수 있다tar -c /path/to/folder | sha1sum
지금까지 가장 빠른 방법은 여전히 타르를 사용하는 것입니다.또, 몇개의 파라메타를 추가하면, 메타데이터에 의한 차이도 해소할 수 있습니다.
GNU tar를 사용하여 dir를 해시하려면 tar 중에 경로를 정렬해야 합니다. 그렇지 않으면 항상 다릅니다.
tar -C <root-dir> -cf - --sort=name <dir> | sha256sum
시간을 무시하다
에는 '접속시간'이나 '변경시간'을합니다.--mtime='UTC 2019-01-01' 모든 타임스탬프가 동일한지 확인합니다.
소유권을 무시하다
이렇게 더하면 요.--group=0 --owner=0 --numeric-owner이치노
일부 파일을 무시하다
--exclude=PATTERN
몇몇 타르는 가지고 있지 않은 것으로 알려져 있다.--sortGNU 타르
견고하고 깨끗한 접근법
- 무엇보다도, 사용 가능한 메모리를 독점하지 마세요!파일 전체를 제공하지 않고 파일을 청크로 해시합니다.
- 다양한 요구/목적에 대한 다양한 접근법(아래의 모든 항목 또는 해당하는 항목 선택):
- 디렉토리 트리의 모든 엔트리의 엔트리 이름만 해시합니다.
- 모든 엔트리의 파일 내용을 해시합니다(inode 번호, ctime, atime, mtime, size 등 메타를 남겨두면 알 수 있습니다).
- 심볼릭 링크의 경우 내용은 참조 이름입니다.해시 처리 또는 건너뛰기 선택
- 항목 내용을 해시하는 동안 심볼 링크(해결된 이름)를 따르는지 여부
- 디렉토리인 경우 내용은 디렉토리 항목일 뿐입니다.재귀적으로 이동하는 동안 해당 수준의 디렉터리 항목 이름을 해시하여 이 디렉터리에 태그를 지정해야 합니까?내용을 해시하기 위해 깊이 이동할 필요 없이 신속하게 변경을 식별하기 위해 해시가 필요한 사용 사례에 유용합니다.예를 들어 파일 이름 변경 등이 있지만 나머지 내용은 그대로 유지되며 모두 상당히 큰 파일입니다.
- 대용량 파일 처리(RAM에 주의)
- 매우 깊은 디렉토리 트리를 처리합니다(열려 있는 파일 기술자에 주의).
- 표준이 아닌 파일 이름 처리
- 소켓, 파이프/FIFO, 블록 디바이스, char 디바이스의 파일은 어떻게 처리합니까?해쉬도 해야 하나요?
- 이동 중에는 어떤 항목의 액세스 시간도 업데이트하지 마십시오. 이러한 경우 부작용이 발생하며 특정 사용 사례에 역효과를 초래할 수 있습니다(직관적?).
제 머릿속에는 이런 것이 있습니다.실제로 이 일에 시간을 할애한 사람이라면 다른 고차나 코너 케이스도 발견했을 것입니다.
여기 있는 툴이 있습니다.메모리는 매우 가볍습니다.대부분의 케이스에 대응하고 있습니다만, 엣지는 다소 거칠 수 있습니다만, 매우 도움이 됩니다.
「 」의 사용 .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
이 이고 git repo에 있는 모든 .gitignore 것 같아요 , 하다, 하다, 하다, 하다.
git ls-files <your_directory> | xargs sha256sum | cut -d" " -f1 | sha256sum | cut -d" " -f1
이거 잘 먹히네요.
파일 이름을 무시하고 파일 내용을 해시하려면
cat $FILES | md5sum
해시를 계산할 때 파일이 같은 순서로 있는지 확인합니다.
cat $(echo $FILES | sort) | md5sum
그러나 파일 목록에 디렉터리를 포함할 수 없습니다.
이를 실현하기 위한 또 다른 도구:
http://md5deep.sourceforge.net/
소리 그대로: md5sum 뿐만 아니라 재귀적 기능, 기타 기능 등입니다.
md5deep -r {direcotory}
이를 위한 python 스크립트가 있습니다.
http://code.activestate.com/recipes/576973-getting-the-sha-1-or-md5-hash-of-a-directory/
알파벳 순서를 변경하지 않고 파일 이름을 변경하면 해시 스크립트는 파일을 검출하지 않습니다.다만, 파일의 순서나 파일의 내용을 변경하면, 스크립트를 실행하면 이전과는 다른 해시가 표시됩니다.
파일 변경을 위해 전체 디렉토리를 체크해야 했습니다.
다만, 타임 스탬프나 디렉토리 소유권은 제외합니다.
파일이 동일한 경우 어디에서나 동일한 합계를 얻는 것이 목표입니다.
다른 머신에 호스트 되는 것도 포함.파일이나 파일 변경은 상관없습니다.
md5sum * | md5sum | cut -d' ' -f1
파일별 해시 목록을 생성한 다음 이러한 해시를 하나로 연결합니다.
이 방법은 tar 방식보다 훨씬 빠릅니다.
해시 내의 프라이버시를 강화하기 위해 동일한 레시피로 sha512sum을 사용할 수 있습니다.
sha512sum * | sha512sum | cut -d' ' -f1
해시 역시 sha512sum을 사용하면 어디에서나 동일하지만 되돌릴 수 있는 방법은 없습니다.
다음은 Python 3의 단순하고 짧은 변형으로, 작은 크기의 파일(예를 들어 모든 파일이 RAM에 쉽게 들어갈 수 있는 소스 트리 등)에 적합하며, 다른 솔루션의 아이디어를 바탕으로 빈 디렉터리를 무시합니다.
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()
다음과 같이 동작합니다.
- 디렉토리의 모든 파일을 반복적으로 찾아 이름별로 정렬합니다.
- 모든 파일의 해시(기본값: SHA-1)를 계산합니다(파일 전체를 메모리로 읽습니다).
- "text=text" 행으로 텍스트 인덱스를 만듭니다.
- 이 인덱스를 UTF-8 바이트 문자열로 인코딩하여 해시합니다.
SHA-1이 마음에 들지 않는 경우 다른 해시 함수를 두 번째 파라미터로 전달할 수 있습니다.
kvantour 답변에 다중 처리 및 진행 표시줄 추가
약 30배 고속 (CPU에 따라 다름)
100%|██████████████████████████████████| 31378/31378 [03:03<00:00, 171.43file/s]
# to hash without permissions
find . -type f -print0 | sort -z | xargs -P $(nproc --all) -0 sha1sum | tqdm --unit file --total $(find . -type f | wc -l) | sort | awk '{ print $1 }' | sha1sum
# to hash permissions
(find . -type f -print0 | sort -z | xargs -P $(nproc --all) -0 sha1sum | sort | awk '{ print $1 }';
find . \( -type f -o -type d \) -print0 | sort -z | xargs -P $(nproc --all) -0 stat -c '%n %a') | \
sort | sha1sum | awk '{ print $1 }'
tqdm이 설치되어 있는지 확인합니다.pip install tqdm 문서를 하십시오.
awk는 부모 또는 을 주지합니다.
이를 위해 작성된 오픈소스 명령줄 도구인 hashdir를 사용해 볼 수 있습니다.
hashdir /folder/of/stuff
여기에는 해시 알고리즘을 지정하고 모든 하위 해시를 인쇄하며 해시를 저장 및 확인할 수 있는 몇 가지 유용한 플래그가 있습니다.
hashdir:
A command-line utility to checksum directories and files.
Usage:
hashdir [options] [<item>...] [command]
Arguments:
<item> Directory or file to hash/check
Options:
-t, --tree Print directory tree
-s, --save Save the checksum to a file
-i, --include-hidden-files Include hidden files
-e, --skip-empty-dir Skip empty directories
-a, --algorithm <md5|sha1|sha256|sha384|sha512> The hash function to use [default: sha1]
--version Show version information
-?, -h, --help Show help and usage information
Commands:
check <item> Verify that the specified hash file is valid.
다음 두 단계로 작성하도록 시도합니다.
- 폴더의 모든 파일에 대해 해시가 있는 파일을 만듭니다.
- 이 파일을 해시하다
다음과 같은 경우:
# 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
에 대한 를 파이프로 합니다.sort하기 위해)로 변경)md5sum ★★★★★★★★★★★★★★★★★」sha1sum어느 쪽을 선택하든.
이걸 위해 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
요약: 전체 폴더의 내용을 해시하거나 두 폴더를 비교하는 방법
# 1. How to get a sha256 hash over all file contents in a folder, including
# hashing over the relative file paths within that folder to check the
# filenames themselves (get this bash function below).
sha256sum_dir "path/to/folder"
# 2. How to quickly compare two folders (get the `diff_dir` bash function below)
diff_dir "path/to/folder1" "path/to/folder2"
# OR:
diff -r -q "path/to/folder1" "path/to/folder2"
"1개의 라이너"
폴더 위치에 관계없이 전체 폴더 내의 모든 비디렉토리 파일 내용에 대해 단일 해시를 가져오려면 주 응답 대신 이 작업을 수행합니다.
이것은 "1 행" 명령어입니다.전체 파일을 복사하여 붙여넣기하여 한 번에 실행할 수 있습니다.
# This one works, but don't use it, because its hash output does NOT
# match that of my `sha256sum_dir` function. I recommend you use
# the "1-liner" just below, therefore, instead.
time ( \
starting_dir="$(pwd)" \
&& target_dir="path/to/folder" \
&& cd "$target_dir" \
&& find . -not -type d -print0 | sort -zV \
| xargs -0 sha256sum | sha256sum; \
cd "$starting_dir"
)
은 나의 해쉬와 낸다.sha256sum_dir아래에 제시된 bash 함수가 생성됩니다.그래서 출력 해시를 정확히 일치시키려면sha256sum_dir츠키다
# Use this one, as its output matches that of my `sha256sum_dir`
# function exactly.
all_hashes_str="$( \
starting_dir="$(pwd)" \
&& target_dir="path/to/folder" \
&& cd "$target_dir" \
&& find . -not -type d -print0 | sort -zV | xargs -0 sha256sum \
)"; \
cd "$starting_dir"; \
printf "%s" "$all_hashes_str" | sha256sum
주 답변이 다른 위치에 있는 동일한 폴더에 대해 동일한 해시를 생성하지 않는 이유에 대한 자세한 내용은 아래를 참조하십시오.
[가 선호하는 방법]과 같다: [어느 정도] bash 함수는 다음과 같다.sha256sum_dir ★★★★★★★★★★★★★★★★★」diff_dir
을 사용하세요.~/.bashrc 또는 내에 .~/.bash_aliases 「」, 「」, 「」를 전제로 ,~/.bashrc 소스:~/.bash_aliases다음과 같이 합니다.
if [ -f ~/.bash_aliases ]; then
. ~/.bash_aliases
fi
아래 두 함수는 모두 제 eRCaGuy_dotfiles repo의 개인 파일에서 찾을 수 있습니다.
.sha256sum_dir함수는 내의 를 가져옵니다.
# Take the sha256sum of all files in an entire dir, and then sha256sum that
# entire output to obtain a _single_ sha256sum which represents the _entire_
# dir.
# See:
# 1. [my answer] https://stackoverflow.com/a/72070772/4561887
sha256sum_dir() {
return_code="$RETURN_CODE_SUCCESS"
if [ "$#" -eq 0 ]; then
echo "ERROR: too few arguments."
return_code="$RETURN_CODE_ERROR"
fi
# Print help string if requested
if [ "$#" -eq 0 ] || [ "$1" = "-h" ] || [ "$1" = "--help" ]; then
# Help string
echo "Obtain a sha256sum of all files in a directory."
echo "Usage: ${FUNCNAME[0]} [-h|--help] <dir>"
return "$return_code"
fi
starting_dir="$(pwd)"
target_dir="$1"
cd "$target_dir"
# See my answer: https://stackoverflow.com/a/72070772/4561887
filenames="$(find . -not -type d | sort -V)"
IFS=$'\n' read -r -d '' -a filenames_array <<< "$filenames"
time all_hashes_str="$(sha256sum "${filenames_array[@]}")"
cd "$starting_dir"
echo ""
echo "Note: you may now call:"
echo "1. 'printf \"%s\n\" \"\$all_hashes_str\"' to view the individual" \
"hashes of each file in the dir. Or:"
echo "2. 'printf \"%s\" \"\$all_hashes_str\" | sha256sum' to see that" \
"the hash of that output is what we are using as the final hash" \
"for the entire dir."
echo ""
printf "%s" "$all_hashes_str" | sha256sum | awk '{ print $1 }'
return "$?"
}
# Note: I prefix this with my initials to find my custom functions easier
alias gs_sha256sum_dir="sha256sum_dir"
개의 할 때, 이 두 개의 디렉토리를 비교할 때 할 수 있습니다.diff -r -q "dir1" "dir2" 이 diff_dir명령어를 입력합니다. 배운 내용입니다.diff여기서 전체 폴더를 비교하는 명령어: Linux에서 두 폴더가 동일한지 확인하는 방법
# Compare dir1 against dir2 to see if they are equal or if they differ.
# See:
# 1. How to `diff` two dirs: https://stackoverflow.com/a/16404554/4561887
diff_dir() {
return_code="$RETURN_CODE_SUCCESS"
if [ "$#" -eq 0 ]; then
echo "ERROR: too few arguments."
return_code="$RETURN_CODE_ERROR"
fi
# Print help string if requested
if [ "$#" -eq 0 ] || [ "$1" = "-h" ] || [ "$1" = "--help" ]; then
echo "Compare (diff) two directories to see if dir1 contains the same" \
"content as dir2."
echo "NB: the output will be **empty** if both directories match!"
echo "Usage: ${FUNCNAME[0]} [-h|--help] <dir1> <dir2>"
return "$return_code"
fi
dir1="$1"
dir2="$2"
time diff -r -q "$dir1" "$dir2"
return_code="$?"
if [ "$return_code" -eq 0 ]; then
echo -e "\nDirectories match!"
fi
# echo "$return_code"
return "$return_code"
}
# Note: I prefix this with my initials to find my custom functions easier
alias gs_diff_dir="diff_dir"
저의 .sha256sum_dir~/temp2).dir(직접 할 수 .)은 폴 is음음음음 you음 is is you you 。b86c66bcf2b033f65451e8c225425f315e618be961351992b7c7681c3822f6a3 에러:
$ gs_sha256sum_dir ~/temp2
real 0m0.007s
user 0m0.000s
sys 0m0.007s
Note: you may now call:
1. 'printf "%s\n" "$all_hashes_str"' to view the individual hashes of each
file in the dir. Or:
2. 'printf "%s" "$all_hashes_str" | sha256sum' to see that the hash of that
output is what we are using as the final hash for the entire dir.
b86c66bcf2b033f65451e8c225425f315e618be961351992b7c7681c3822f6a3
은 ᄃ자 cmd와 입니다.diff_dir두 디르를 비교하여 동등함을 확인합니다.이것은, 디렉토리 전체를 SD카드에 카피하는 것이 올바르게 동작하고 있는 것을 확인합니다.에 가가한 i로 표시했다.Directories match!★★★★★★★★★★★★★★★★★:
$ gs_diff_dir "path/to/sd/card/tempdir" "/home/gabriel/tempdir"
real 0m0.113s
user 0m0.037s
sys 0m0.077s
Directories match!
주 답변이 다른 위치에 있는 동일한 폴더에 대해 동일한 해시를 생성하지 않는 이유
여기서 가장 높은 평가를 받은 답변을 시도했지만, 현재로선 잘 되지 않습니다.좀 수정해야겠어요.관심 폴더의 기본 경로에 따라 해시가 변경되므로 제대로 작동하지 않습니다.즉, 일부 폴더의 동일한 복사본은 두 폴더가 완전히 일치하고 동일한 내용을 포함하더라도 복사된 폴더와는 다른 해시를 가집니다.두 개의 동일한 폴더의 해시가 다를 경우 폴더의 해시를 얻는 목적을 달성하지 못합니다.설명하겠습니다.
를 들어, 폴더 이 ''고 가정해 .temp2~/temp2용 .가 포함되어 있습니다.file1.txt,file2.txt , , , , 입니다.file3.txtfile1.txt가 있다a에 반환, 반환,file2.txt가 있다b이 이어집니다.또, 「 」를 참조해 주세요.file3.txt가 있다c그 후에 돌아오다.
★★★★★★★를 실행했을 경우find /home/gabriel/temp2해했습습니니다
$ find /home/gabriel/temp2
/home/gabriel/temp2
/home/gabriel/temp2/file3.txt
/home/gabriel/temp2/file1.txt
/home/gabriel/temp2/file2.txt
을 가가그에 전송하면sha256sum)sha1sum주요 답변과 같은 패턴으로, 다음과 같습니다.각 해시 뒤에 풀패스가 있습니다.이러한 패스는 필요 없습니다.
$ find /home/gabriel/temp2 -type f -print0 | sort -z | xargs -0 sha256sum
87428fc522803d31065e7bce3cf03fe475096631e5e07bbd7a0fde60c4cf25c7 /home/gabriel/temp2/file1.txt
0263829989b6fd954f72baaf2fc64bc2e2f01d692d4de72986ea808f6e99813f /home/gabriel/temp2/file2.txt
a3a5e715f0cc574a73c3f9bebb6bc24f32ffd5b67b387244c2c909da779a1478 /home/gabriel/temp2/file3.txt
다음 위의 을 " "로 "sha256sum파일 해시가 전체 파일 경로로 되어 있는데, 이는 우리가 원하는 것이 아닙니다!파일 해시는 폴더와 해당 폴더의 복사본에서 정확히 일치할 수 있지만 절대 경로가 정확히 일치하지 않으므로 단일 최종 해시의 일부로 전체 파일 경로에 대해 해시를 생성하기 때문에 다른 최종 해시를 생성합니다.
대신 각 해시 옆에 있는 상대 파일 경로가 필요합니다.그러기 위해서는 먼저cdhash 명령어를 모든 파일에 대해 다음과 같이 실행합니다.
cd "/home/gabriel/temp2" && find . -type f -print0 | sort -z | xargs -0 sha256sum
자, 이제 이해해요.파일 경로가 모두 상대적인 것에 주의해 주세요.이것이 제가 원하는 것입니다.
$ cd "/home/gabriel/temp2" && find . -type f -print0 | sort -z | xargs -0 sha256sum
87428fc522803d31065e7bce3cf03fe475096631e5e07bbd7a0fde60c4cf25c7 ./file1.txt
0263829989b6fd954f72baaf2fc64bc2e2f01d692d4de72986ea808f6e99813f ./file2.txt
a3a5e715f0cc574a73c3f9bebb6bc24f32ffd5b67b387244c2c909da779a1478 ./file3.txt
좋습니다. 출력 문자열 전체를 해시하면 파일 경로가 모두 상대적이므로 최종 해시는 폴더와 해당 복사본에 정확히 일치합니다.이와 같이, 파일의 내용이 다르거나 파일명이 다르거나, 또는 양쪽 모두의 경우에, 특정의 폴더에 대해서 다른 해시를 취득하기 위해서, 파일의 내용과 디렉토리내의 파일명을 해시 합니다.
수 있다sha1sum 값 후 " " "를 클릭합니다.sha1sum정확히 무엇을 달성하고 싶은지에 따라 다르죠
파일명과 그 내용을 포함한 전체 디렉토리의 모든 파일을 해시하는 방법
예를 들어 폴더와 폴더의 모든 내용을 비교하여 컴퓨터에서 다른 컴퓨터로 올바르게 복사되었는지 확인하려고 하면 다음과 같이 할 수 있습니다.을 '아까보다'라고 mydir 지금 path에 and and 、 and 、 습 、 and 、 and and 。/home/gabriel/mydir과 '1'에서/home/gabriel/dev/repos/mydir2번으로 하다.
# 1. First, cd to the dir in which the dir of interest is found. This is
# important! If you don't do this, then the paths output by find will differ
# between the two computers since the absolute paths to `mydir` differ. We are
# going to hash the paths too, not just the file contents, so this matters.
cd /home/gabriel # on computer 1
cd /home/gabriel/dev/repos # on computer 2
# 2. hash all files inside `mydir`, then hash the list of all hashes and their
# respective file paths. This obtains one single final hash. Sorting is
# necessary by piping to `sort` to ensure we get a consistent file order in
# order to ensure a consistent final hash result.
find mydir -type f -exec sha256sum {} + | sort | sha256sum
# Optionally pipe that output to awk to filter in on just the hash (first field
# in the output)
find mydir -type f -exec sha256sum {} + | sort | sha256sum | awk '{print $1}'
바로 그거야!
학습을 위해 파일 해시의 중간 목록을 보려면 다음을 실행하십시오.
find mydir -type f -exec sha256sum {} + | sort
위의 명령어는 빈 디렉토리, 파일 권한, 파일이 마지막으로 편집된 시점의 타임스탬프 등을 무시합니다.하지만 대부분의 경우 괜찮습니다.
예
을 사용하다는 내 것을 하고 .eclipse-workspace폴더가 한 컴퓨터에서 다른 컴퓨터로 올바르게 복사되었습니다.바와 같이 '하다'는time명령어를 실행하면 11.790초가 걸린 것으로 나타납니다.
$ time find eclipse-workspace -type f -exec sha256sum {} + | sort | sha256sum
8f493478e7bb77f1d025cba31068c1f1c8e1eab436f8a3cf79d6e60abe2cd2e4 -
real 0m11.790s
user 0m11.372s
sys 0m0.432s
'해시하다'입니다.8f493478e7bb77f1d025cba31068c1f1c8e1eab436f8a3cf79d6e60abe2cd2e4
배관하는 awk외외 and and를 time해했습습니니다
$ find eclipse-workspace -type f -exec sha256sum {} + | sort | sha256sum | awk '{print $1}'
8f493478e7bb77f1d025cba31068c1f1c8e1eab436f8a3cf79d6e60abe2cd2e4
체크해주세요find된 가 있는 stderr에 '가 생성될 수 있습니다.finddiscloss.disclosed 입니다.
로 eclipse-workspace다음과 같이 6480개의 파일이 포함되어 있는 것을 고려하면 불과 12초의 dir는 매우 인상적입니다.
find eclipse-workspace -type f | wc -l
...사이즈는 다음과 같이 3.6GB입니다.
du -sh eclipse-workspace
「 」를 참조해 주세요.
- 또 다른 답변은 위의 정보를 사용하는 것입니다.: Linux에서 두 폴더가 동일한지 확인하는 방법
기타 크레딧:위의 몇 가지를 배우기 위해 ChatGPT와 채팅했습니다.그러나 위의 모든 작업과 텍스트는 제가 작성하고 테스트하고 검증한 것입니다.
언급URL : https://stackoverflow.com/questions/545387/linux-compute-a-single-hash-for-a-given-folder-contents
'programing' 카테고리의 다른 글
| SQL Server - 업데이트 시 내부 가입 (0) | 2023.04.11 |
|---|---|
| iOS 6에서 지도 앱을 프로그래밍 방식으로 엽니다. (0) | 2023.04.11 |
| Postgres DB Size 명령어 (0) | 2023.04.11 |
| 특정 문자열을 클립보드에 복사하기 위한 Excel VBA 코드 (0) | 2023.04.11 |
| Postgres의 기본 키 시퀀스가 동기화되지 않을 때 어떻게 재설정합니까? (0) | 2023.04.11 |