掌握基礎語法后,嘗試使用python的zipfile模塊練手。
zipfile是Python里用來做zip格式編碼的壓縮和解壓縮的。
這里將大體的思路分解成四段代碼,逐一完善功能;
第一段代碼:解壓zip
首先了解python解壓zip文件的庫
import zipfile
# 定義通用解壓函數
def tryZipPwd(zFile,savePath,pw =None):
# 如果密碼是空就直接解壓,使用異常判斷
try:
# 如果密碼為空就直接解壓
if pw == None:
zFile.extractall(path=savePath)
else:
# 將密碼轉換為utf-8編碼
zFile.extractall(path=savePath,pwd=pw.encode('utf-8'))
print('[+] ZIp文件解壓成功,密碼:%s' %(pw))
return True
except:
print('[-]Zip文件解壓失敗,密碼:%s' % (pw))
return False
第二段 解壓zip函數的使用
將通用解壓zip的函數,傳入參數引用就可以了
# 指定密碼打開Zip文件,密碼是123qwer
#with zipfile.ZipFile('C:/Users/Windows32/Desktop/untitled/sucess.zip') as zFile:
# tryZipPwd(zFile,'C:/Users/Windows32/Desktop/untitled/','1234qwer')
第三段代碼 讀取文件內容
python逐行讀取文件內容的三種方法;
方法1:
f = open("foo.txt") # 返回一個文件對象
line = f.readline() # 調用文件的 readline()方法
while line:
print line, # 后面跟 ',' 將忽略換行符
# print(line, end = '') # 在 Python 3中使用
line = f.readline()
f.close()
方法2:
for line in open("foo.txt"):
print line,
方法3:
f = open("c:\\1.txt","r")
lines = f.readlines()#讀取全部內容
for line in lines
print line
第四段代碼-讀取密碼文本,批量傳入密碼嘗試解壓zip文件
綜合以上的代碼就可以實現zip壓縮包的密碼破解了,pass.txt是CSDN泄露的TOP100常用密碼,寫了for循環與while循環的代碼;
# -*- coding: utf-8 -*-
import zipfile
# 定義通用解壓函數
def tryZipPwd(zFile,savePath,pw =None):
try:
if pw == None:
zFile.extractall(path=savePath)
else:
zFile.extractall(path=savePath,pwd=pw.encode('utf-8'))
print('[+] ZIp文件解壓成功,密碼:%s' %(pw))
return True
except:
# print('[-]Zip文件解壓失敗,密碼:%s' % (pw))
return False
# 指定密碼打開Zip文件
#with zipfile.ZipFile('C:/Users/Windows32/Desktop/untitled/sucess.zip') as zFile:
# tryZipPwd(zFile,'C:/Users/Windows32/Desktop/untitled/','1234qwer')
# 逐行讀取文本里的密碼,然后傳入通用解壓函數中
passFile = open('C:/Users/Windows32/Desktop/untitled/pass1.txt')
# for循環
# 當破解成功后退出程序與關閉文件流
for i in open('C:/Users/Windows32/Desktop/untitled/pass1.txt'):
# 將文本里的換行清除
password = i.strip('\n')
with zipfile.ZipFile('C:/Users/Windows32/Desktop/untitled/sucess.zip') as zFile:
# 傳回函數執行狀態,如果返回結果為真,就代表解壓zip文件成功,輸出當前的密碼
flag = tryZipPwd(zFile,'C:/Users/Windows32/Desktop/untitled/',password)
if flag:
print("sucess pass is %s" % (i))
exit(0)
passFile.close()
i = passFile.readline()
passFile.close()
# while循環
line = passFile.readline()
while line:
line = line.strip('\n')
with zipfile.ZipFile('C:/Users/Windows32/Desktop/untitled/sucess.zip') as zFile:
flag = tryZipPwd(zFile,'C:/Users/Windows32/Desktop/untitled/',line)
if flag:
print("sucess pass is %s" % (line))
exit(0)
passFile.close()
line = passFile.readline()
passFile.close()