Python 3: Write to stdout in binary mode

Python scripts are often used to generate payloads for attacks, e.g. buffer overflows. Also, it is useful to send the payload to stdout, so that it can be redirected to the target process or, for different kinds of attacks, saved to a file.

However, since Python 3 all strings (type str) are encoded in Unicode and the print() function does not print binary data (types bytes or bytearray) directly, but only its representation, which looks like b’…’:

Writing to stdout directly doesn’t even work:

The solution is to write to stdout’s underlying binary buffer:

Alternatively, you can simply write to a file opened in binary mode instead:

Leave a comment

Your email address will not be published. Required fields are marked *