앞서 파이썬 개발 도구인 파이참 설치에 대해 설명했습니다.
이번에는 파이썬을 이용하여 각 file의 MD5 hash를 구하는 파이썬 프로그램을 작성해보려고 합니다.
1. MD5 hash를 얻기 위한 메소드, getHash를 만들어야 합니다.
def getHash(path, blocksize=65536):
afile = open(path, 'rb')
hasher = hashlib.md5()
buf = afile.read(blocksize)
while len(buf) > 0:
hasher.update(buf)
buf = afile.read(blocksize)
afile.close()
return hasher.hexdigest()
이 부분에서는 hashlib을 import해야 합니다.
2. 런타임 환경에서 파일 정보를 받아 hashfile 메소드로 넘기는 역할을 하는 로직을 짜야합니다.
file = sys.argv[1]
if os.path.exists(file):
fileHash = getHash(file)
print(fileHash)
else:
print('%s is not a valid path, please verify' % file)
sys.exit()
이 부분에서는 os, sys를 import해야 합니다.
최종 코드입니다.
import os, sys
import hashlib
def getHash(path, blocksize=65536):
afile = open(path, 'rb')
hasher = hashlib.md5()
buf = afile.read(blocksize)
while len(buf) > 0:
hasher.update(buf)
buf = afile.read(blocksize)
afile.close()
return hasher.hexdigest()
file = sys.argv[1]
if os.path.exists(file):
fileHash = getHash(file)
print(fileHash)
else:
print('%s is not a valid path, please verify' % file)
sys.exit()
실행 결과
# python3 hashTest.py testfile.dat XXXXae74c59511ea921692349e2eXXXX