CuriousDeveloper
CuriousDeveloper

Reputation: 899

How to echo hex from python

I get TypeError: must be string without null bytes, not str when I run this code. I want to echo the hexadecimal code

#!/usr/bin/python

import os

test = '\x76\x06\x40\x00'
cmd = "echo '"+test+"'"
os.system(cmd)

I have tried various echo flags like -e along with r in python but it just ends up echoing \x76\x06\x40\x00 and not the actual characters.

The code works fine if I change the \x00 (null) to something like \x0A

Upvotes: 1

Views: 350

Answers (2)

EchoMike444
EchoMike444

Reputation: 1692

you can use the module binascii ( https://docs.python.org/2/library/binascii.html )

#!/usr/bin/python
import binascii
test = '\x76\x06\x40\x00'
print( "%s\n" % binascii.hexlify(test)  )

Version with shell call

#!/usr/bin/python
import binascii
import os
test = '\x76\x06\x40\x00'
print( "from python:%s\n" % binascii.hexlify(test)  )
cmd = "echo 'from shell:"+("%s\n" % binascii.hexlify(test))+"'"
os.system(cmd)

Upvotes: 0

Bhakta Raghavan
Bhakta Raghavan

Reputation: 725

why do you need to echo? You can print from your python program and | another command

$ cat x.py
#!/usr/bin/python

import os

print '0x10'
print '0x20'

$ ./x.py  | wc -l
   2

Or maybe I am not getting the question?

Upvotes: 1

Related Questions