驗證軟件一致性的Python腳本

一般軟件公司在發佈軟件前會將生產環境要發佈的軟件包和測試環境最後測試後的包做一個比對以驗證要發佈包的正確性,可以通過對比兩個軟件包的MD5值來實現,因爲原包的一點不同將會其對應MD5值就會有較大差異。但是如果僅僅是一對MD5值得比較還簡單,如果一次要比較較多的軟件包時就會有較大的工作量,可以通過下面這個小腳本輕鬆實現軟件包的對比

需要輸入的信息有:

線上軟件包的下載到的目的文件夾

線上軟件包下載鏈接寫入一個文本文件,每行一個。

本地軟件包所在目錄

#!/usr/bin/env/python  
# -*- coding: utf-8 -*-

import os  
import time    
import urllib    
import hashlib

#創建測試文件下載目錄,如果存在則不需要創建  
def Generatedirectory(dirname):    
   if not os.path.exists(dirname):    
       os.mkdir(dirname)    
       print 'Create the test dirs %s OK!' %(dirname)    
   else:    
       print 'The test dirs %s alreay exist!' %(dirname)

#讀取文件,取得文件內容列表    
def Readfile(filename):    
   file=open(filename,'r')    
   list=file.readlines()    
   file.close()    
   return list

#下載測試文件  
def Downloadfiles(url,dirname,basename):    
   downloadfilename=os.path.join(dirname,basename)    
   urllib.urlretrieve(url,downloadfilename)    
   return downloadfilename

#生成文件的MD5值  
def md5_file(name):    
   m=hashlib.md5()    
   rfile=open(name,'rb')    
   m.update(rfile.read())    
   rfile.close()    
   md5=m.hexdigest()    
   return md5

#將生成的MD5值寫入文件  
def Writemd5_file(filename,value):    
   fopen=open(filename,'a')    
   fopen.write(value+'\n')    
   fopen.close()


#讀取目錄中文件,以列表形式返回內容    
def Readfileofdirectory(dirname):    
   localfile=os.listdir(dirname)    
   list=[]    
   for lf in localfile:    
       localfilepath=os.path.join(dirname,lf)    
       list.append(localfilepath)    
   return list    
   

dirname=raw_input('請輸入下載到哪個目錄:')  
Generatedirectory(dirname)    
linkfile=raw_input('請輸入存放鏈接地址的文件名:')    
urllist=Readfile(linkfile)

#basename=raw_input('please input the downloadfilename:')  
currenttime=time.strftime('%Y-%m-%d',time.localtime())    
md5filebasename='md5_file'+currenttime+'.txt'    
md5filename=os.path.join(dirname,md5filebasename)    
for url in urllist:    
   url=url.strip('\n')    
 
   basename=url[-8:]    
   downloadfilename=Downloadfiles(url,dirname,basename)    
   df_md5=md5_file(downloadfilename)    
   
   Writemd5_file(md5filename,df_md5)

localfilepath=raw_input('請輸入本地軟件包的存放目錄:')  
localmd5basename='md5_file'+currenttime+'.txt'    
localmd5=os.path.join(localfilepath,localmd5basename)    
lf=Readfileofdirectory(localfilepath)

for f in lf:  
   lf_md5=md5_file(f)    
   Writemd5_file(localmd5,lf_md5)    
   

dmd5list=Readfile(md5filename)  
lmd5list=Readfile(localmd5)    
   

dmd5list.sort()  
lmd5list.sort()    
print dmd5list    
print lmd5list    
if cmp(dmd5list,lmd5list)==0:    
   print 'Matched'    
else:    
   print 'Failed'

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章