user1111111111111
user1111111111111

Reputation: 68

Python shutil, complete file is not getting written to archive. Tried zipfile also

I have following code:

import os
import sys
import shutil
import binascii
import zipfile

code = "testing111"

head1 = ("\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01")
head2 = ("\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01")
head3 = ("\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01")

evilbuff = bytearray(head1)
evilbuff += code
evilbuff += bytearray(head2)
evilbuff += code
evilbuff += bytearray(head3)

file = "folder\\file\\demo\\images.png"
f = open(file,mode='wb')
f.write(evilbuff)

file2 = sys.argv[2]
shutil.make_archive("myzip", "zip", "demo_03")
print ("[+] Done")

I'm trying to write a file in folder_03\file\demo\ and then zip the contents of folder_03 folder. Everything is working fine.

There is just one problem. The file images.jpg is stripped at the end.

It's getting written as expected in folder\file\demo\images.jpg but in the zip archive the file is not complete. Around 300 bytes are stripped from the end. Is it some bug in the python zip utility? I also tried with zipfile but had the same issue.

The bytes in head1, head2, head3 here are just examples.

Upvotes: 0

Views: 207

Answers (1)

Dušan Maďar
Dušan Maďar

Reputation: 9859

You are not closing the file. Use f.close() after you write the file, or even better, use a context manager.

import os
import sys
import shutil
import binascii
import zipfile

code = "testing111"

head1 = ("\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01")
head2 = ("\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01")
head3 = ("\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01")

evilbuff = bytearray(head1)
evilbuff += code
evilbuff += bytearray(head2)
evilbuff += code
evilbuff += bytearray(head3)

file = "folder\\file\\demo\\images.png"
with open(file, mode='wb') as file_object:
    file_object.write(evilbuff)

file2 = sys.argv[2]
shutil.make_archive("myzip", "zip", "demo_03")
print ("[+] Done")

Upvotes: 1

Related Questions