Search code examples
python-3.xhexdump

Achieve Hexdump in python


How can I achieve the following in Python 3?

cat file | sigtool –hex-dump | head -c 2048

I’m attempting to read a .ndb database which I have created in order to check for malicious PHP files, however I need to be able to create hex signatures of files in python in order to check against this database.


Solution

  • Try using the binascii.hexlify function:

    import binascii
    
    # get the filename from somewhere
    
    # read the raw bytes
    with open(filename, 'rb') as f:
        raw_bytes = f.read(1024)       # two hex digits per byte, so read 1024
    
    # convert to hex
    hex_bytes = binascii.hexlify(raw_bytes)  # this will be 2048 bytes long
    
    # use the hex, as desired
    hex_str = hexbytes.decode('ascii') # hexidecimal uses a subset of ASCII
    print(hex_str)                     # or put this in a database, or whatever
    

    I converted the hex_bytes into a string so I could print them out, but you might omit that if you can use the bytes object returned by hexlify directly (e.g. writing it to a file in binary mode, or saving it directly into a database).