2013-06-01 224 views
41

我在python中創建了一個代碼,用於檢查文件中的md5,並確保md5與原始文件匹配。以下是我已經開發:如何計算Python中文件的md5校驗和?

#Defines filename 
filename = "file.exe" 

#Gets MD5 from file 
def getmd5(filename): 
    return m.hexdigest() 

md5 = dict() 

for fname in filename: 
    md5[fname] = getmd5(fname) 

#If statement for alerting the user whether the checksum passed or failed 

if md5 == '>md5 will go here<': 
    print("MD5 Checksum passed. You may now close this window") 
    input ("press enter") 
else: 
    print("MD5 Checksum failed. Incorrect MD5 in file 'filename'. Please download a new copy") 
    input("press enter") 
exit 

但每當我運行代碼,我得到如下:

Traceback (most recent call last): 
File "C:\Users\Username\md5check.py", line 13, in <module> 
md5[fname] = getmd5(fname) 
File "C:\Users\Username\md5check.py, line 9, in getmd5 
    return m.hexdigest() 
NameError: global name 'm' is not defined 

有什麼我在我的代碼失蹤?

+0

[生成文件的MD5校驗和?]的可能的重複?(http://stackoverflow.com/questions/3431825/generating-a-md5-checksum-of-a-file) – pylover

回答

108

關於您的錯誤以及代碼中缺少的內容。 m是沒有爲getmd5()函數定義的名稱。沒有冒犯,我知道你是初學者,但是你的代碼遍佈全球。讓我們逐個看看你的問題:)首先,你沒有正確使用hashlib.md5.hexdigest()方法。請查找關於haslib函數Python Doc Library的解釋。返回MD5用於提供正確的方法是做這樣的事情:

>>> import hashlib 
>>> hashlib.md5("filename.exe").hexdigest() 
'2a53375ff139d9837e93a38a279d63e5' 

但是,您在這裏有更大的問題。您正在計算一個文件名字符串的MD5,其中實際上MD5是基於文件內容計算的。你將需要基本讀取文件內容並通過md5管道。我的下一個例子不是很高效,但類似的:

>>> import hashlib 
>>> hashlib.md5(open('filename.exe','rb').read()).hexdigest() 
'd41d8cd98f00b204e9800998ecf8427e' 

正如你可以清楚地看到第二個MD5哈希與第一個完全不同。原因是我們正在推送文件的內容,而不僅僅是文件名。一個簡單的解決方案可能是類似的東西:

# Import hashlib library (md5 method is part of it) 
import hashlib  

# File to check 
file_name = 'filename.exe'  

# Correct original md5 goes here 
original_md5 = '5d41402abc4b2a76b9719d911017c592' 

# Open,close, read file and calculate MD5 on its contents 
with open(file_name) as file_to_check: 
    # read contents of the file 
    data = file_to_check.read()  
    # pipe contents of the file through 
    md5_returned = hashlib.md5(data).hexdigest() 

# Finally compare original MD5 with freshly calculated 
if orginal_md5 == md5_returned: 
    print "MD5 verified." 
else: 
    print "MD5 verification failed!." 

請看後Python: Generating a MD5 checksum of a file它詳細闡述了幾種方式如何,可以有效地實現。

祝你好運。

+0

哇。我感到很尷尬。我想我把錯誤的代碼放在我正在做的事情上,並且隨之增加了很多錯誤。謝謝你的幫助。我雖然更習慣批量和lua。所以Python對我來說很挑剔。 – user2344996

+10

您還應該使用open(file_name,'rb')以二進制模式打開文件,否則當os執行換行/回車轉換時您可能會遇到問題。請參閱https://mail.python.org/pipermail/tutor/2004-January/027634.html和http://stackoverflow.com/questions/3431825/python-generating-a-md5-checksum-of-a-file ?rq = 1 – twobeers

+3

如果你在一個二進制文件中工作,確保你使用'b'模式正確讀取它,最後我使用這個函數按預期工作:hashlib.sha512(open(fn,'rb')。read ())。hexdigest() –