0

I try to convert a hex string to shellcode format For example: I have a file in hex string like aabbccddeeff11223344 and I want to convert that through python to show this exact format: "\xaa\xbb\xcc\xdd\xee\xff\x11\x22\x33\x44" including the quotes "".

My code is:

with open("file","r") as f:
    a = f.read()
    b = "\\x".join(a[i:i+2] for i in range(0, len(a), 2))
    print b

so my output is aa\xbb\xcc\xdd\xee\xff\x11\x22\x33\x44\x.

I understand I can do it via sed command but I wonder how I may accomplish this through python.

1 Answer 1

2

The binascii standard module will help here:

import binascii

print repr(binascii.unhexlify("aabbccddeeff11223344"))

Output:

>>> print repr(binascii.unhexlify("aabbccddeeff11223344"))
'\xaa\xbb\xcc\xdd\xee\xff\x11"3D'
Sign up to request clarification or add additional context in comments.

6 Comments

Thank you. So the output is missing \x22\x33\x44. I got the error "Type Error: Odd-length string".
@kluo, no, the output of the code in my answer is not missing anything and the code is not causing any errors. Please double-check how you run it and keep in mind that '\x44' == 'D', '\x33' == '3' and '\x22' == '"', which is exactly what this code produces.
Oh I see. Can we keep the original hex format somehow?
@kluo, I believe there's no need to: the compiler will deal with the mix of hex-escapes and literal ASCII characters just fine. They are the same thing.
I have put aabbccddeeff11223344 to a file call 'test': and following code: import binascii with open ("test","r") as f: a = f.read() b = repr(binascii.unhexlify(a)) print b and I got TypeError: Odd length string. That's weird
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.