本文整理汇总了Python中zipfile.ZipFile.setpassword方法的典型用法代码示例。如果您正苦于以下问题:Python ZipFile.setpassword方法的具体用法?Python ZipFile.setpassword怎么用?Python ZipFile.setpassword使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类zipfile.ZipFile
的用法示例。
在下文中一共展示了ZipFile.setpassword方法的4个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: fetch_attachment
# 需要导入模块: from zipfile import ZipFile [as 别名]
# 或者: from zipfile.ZipFile import setpassword [as 别名]
def fetch_attachment(self, attribute_id, uuid, event_uuid, filename):
url = '{0}/attributes/download/{1}'.format(self.api_url, attribute_id)
try:
result = None
req = urllib2.Request(url, None, self.api_headers)
resp = urllib2.urlopen(req).read()
binary = StringIO(resp)
zipfile = True
try:
zip_file = ZipFile(binary)
zip_file.setpassword('infected'.encode('utf-8'))
except BadZipfile:
zipfile = False
if self.dump:
path = self.__get_dump_path(self.file_location, event_uuid)
destination_folder = '{0}/{1}'.format(path, '')
if not isdir(destination_folder):
makedirs(destination_folder)
# save zip file
if zipfile:
f = open('{0}/{1}.zip'.format(destination_folder, filename), 'w+')
f.write(resp)
f.close()
extraction_destination = '{0}/{1}.zip_contents'.format(destination_folder, filename)
if not isdir(extraction_destination):
makedirs(extraction_destination)
# unzip the file
zip_file.extractall(extraction_destination)
else:
file_path = '{0}/{1}'.format(destination_folder, filename)
f = open(file_path, 'w+')
f.write(resp)
f.close()
extraction_destination = '{0}'.format(destination_folder)
if not isdir(extraction_destination):
makedirs(extraction_destination)
move(file_path, extraction_destination)
if zipfile:
zipfiles = zip_file.filelist
for zipfile in zipfiles:
filename = zipfile.filename
result = zip_file.read(filename)
break
zip_file.close()
else:
result = resp
return result
except urllib2.HTTPError:
return None
示例2: add
# 需要导入模块: from zipfile import ZipFile [as 别名]
# 或者: from zipfile.ZipFile import setpassword [as 别名]
def add(self, archive_password=None, audio_file=None, session=None, artist_name_fallback=None):
cache_key = LibraryUpload.CACHE_KEY % (cherrypy.request.user.id, session)
all_tracks = None
if not cache.has(cache_key):
raise cherrypy.HTTPError(status=409)
else:
all_tracks = cache.get(cache_key)
if audio_file is not None and len(audio_file) == 0:
audio_file = None
if archive_password is not None and len(archive_password) == 0:
archive_password = None
content_disposition = cherrypy.request.headers.get('content-disposition')
filename = content_disposition[content_disposition.index('filename=') + 9:]
if filename.startswith('"') and filename.endswith('"'):
filename = filename[1:-1]
filename = unquote(filename)
ext = os.path.splitext(filename)[1].lower()[1:]
basename = os.path.splitext(filename)[0]
cache_path = os.path.join(cherrypy.config['opmuse'].get('cache.path'), 'upload')
if not os.path.exists(cache_path):
os.mkdir(cache_path)
tempdir = tempfile.mkdtemp(dir=cache_path)
path = os.path.join(tempdir, filename)
paths = []
rarfile.PATH_SEP = '/'
messages = []
with open(path, 'wb') as fileobj:
fileobj.write(cherrypy.request.rfile.read())
# this file is a regular file that belongs to an audio_file
if audio_file is not None:
track = None
tries = 0
# try and sleep until we get the track.. this will almost always
# be needed because of the async upload.
while track is None and tries < 10:
track = library_dao.get_track_by_filename(audio_file.encode('utf8'))
tries += 1
if track is None:
time.sleep(3)
if track is None:
messages.append(('warning', ("<strong>%s</strong>: Skipping <strong>%s</strong>, timeout trying to " +
"find its track.") % (audio_file, filename)))
else:
track_structure = TrackStructureParser(track)
track_path = track_structure.get_path(absolute=True)
relative_track_path = track_structure.get_path(absolute=False).decode('utf8', 'replace')
new_path = os.path.join(track_path, filename.encode('utf8'))
if os.path.exists(new_path):
messages.append(('warning', ("<strong>%s</strong>: Skipping <strong>%s</strong>, already exists " +
"in <strong>%s</strong>.") % (audio_file, filename, relative_track_path)))
else:
shutil.move(path.encode('utf8'), new_path)
messages.append(('info', ("<strong>%s</strong>: Uploaded <strong>%s</strong> to " +
"<strong>%s</strong>.") % (audio_file, filename, relative_track_path)))
elif ext == "zip":
# set artist name fallback to zip's name so if it's missing artist tags
# it's easily distinguishable and editable so it can be fixed after upload.
artist_name_fallback = basename
try:
zip = ZipFile(path)
if archive_password is not None:
zip.setpassword(archive_password.encode())
zip.extractall(tempdir)
os.remove(path)
for name in zip.namelist():
namepath = os.path.join(tempdir, name)
# ignore hidden files, e.g. OSX archive weirdness and such
if name.startswith(".") or os.path.split(name)[0] == "__MACOSX":
shutil.rmtree(namepath)
continue
#.........这里部分代码省略.........
示例3: __init__
# 需要导入模块: from zipfile import ZipFile [as 别名]
# 或者: from zipfile.ZipFile import setpassword [as 别名]
class ZipHintCracker:
def __init__(self, passCandidate, zipPath, hashPath):
self.pwdHint = passCandidate
self.zipInfo = ZipFile(zipPath, "r")
self.loadPermutations(hashPath)
#tests a password on a given zip file
def testPwd(self, pwd, checkMethod=ZipFile.testzip):
self.zipInfo.setpassword(pwd)
try:
checkMethod(self.zipInfo)
#if no exception was raised, it was the right password
return True
except RuntimeError as err:
#if it's not the right password, intercept the runtime error
if err[0] == 'Bad password for file':
return False
#the runtime error was not one we expected, re-raise it
else:
raise
#test all elements in a table (or iterateable ;))
def testTable(self,table):
for i in table:
if self.testPwd(i): #if it's the right password
return i #return the password
return False #otherwise return False
#test the hint string
def testHint(self):
return self.testTable(self.permuteHint())
#set up the hash from a json file of possible substitution
def loadPermutations(self,path):
with open(path) as f:
self.permHash = json.load(f)
#permute a given character based on a dictionary of known substitutions
# is a generator, so this function returns an iteratable object
def permuteCharacter(self,char):
if(char): #as long as we're not dealing with "" (empty string)
if(char.isalpha()): #yield both cases of any alphabetical character
yield char.upper()
yield char.lower()
#if the character is in the hash then run through all its members
else:
yield char
if(type(self.substitutions.get(char)) == list):
for perm in self.substitutions.get(char):
yield perm
#permute a given string based on a dictionary of known substitutions
# is a generator, so it's used in for loops
def permuteString(self, string):
char = string[:1]
rest = string[1:]
if(len(string)> 1):
for permutation in self.permuteCharacter(char):
for restPermutation in self.permuteString(rest):
yield permutation+restPermutation
else:
for permutation in self.permuteCharacter(char):
yield permutation
def permuteHint(self):
return self.permuteString(self.pwdHint)
示例4: len
# 需要导入模块: from zipfile import ZipFile [as 别名]
# 或者: from zipfile.ZipFile import setpassword [as 别名]
# print r.status_code
# print r.reason
# dat = r.content
# print dat[:100]
# print len(dat)
# f = open('unreal.zip', 'wb')
# f.write(dat)
# f.close()
f = open('unreal.zip', 'rb')
dat = f.read()
f.close()
print dat[:100]
print len(dat)
z = ZipFile(StringIO.StringIO(dat))
print z.namelist()
z.setpassword(password)
z.extractall(path='./ch21_files/')
z.close()