domingo, 9 de febrero de 2014

[How to] Unzip files in RAM memory

Is very easy unzip files, you can found many examples on internet, but here is one which works perfect for me.

Here you have a POC:

import requests 
import tempfile 
import zipfile  

zip = requests.get(zip_file_url)

temp = tempfile.TemporaryFile()
temp.write(zip.content)
temp.seek(0) 

zfile = zipfile.ZipFile(temp)

#set password if needed 
zfile.setpassword('infected') 
 
for name in zfile.namelist():
    ram_file = zfile.open(name).read()

temp.close()

For large files you can use:
import requests
import tempfile
import zipfile

zip  = requests.get(zip_file_url)
temp = tempfile.TemporaryFile()

content = ''

for block in zip.iter_content(1048576):
    
    if not block:
        break
        
    content += block
    
temp.write(content)
temp.seek(0)

zfile = zipfile.ZipFile(temp)

#set password if needed
zfile.setpassword('infected')

for name in zfile.namelist():
    ram_file = zfile.open(name).read()
    
temp.close()
with this don't work :(
with tempfile.TemporaryFile() as temp
    for block in zip.iter_content(1048576):
    
        if not block:
            break
        
        temp.write(block)


For more information about tempfile look here

Best regards

No hay comentarios:

Publicar un comentario