CLI: Write byte at address (hexedit/modify binary from the command line)

巧了我就是萌 提交于 2019-11-27 18:20:45
printf '\x31\xc0\xc3' | dd of=test_blob bs=1 seek=100 count=3 conv=notrunc 

dd arguments:

  • of | file to patch
  • bs | 1 byte at a time please
  • seek | go to position 100 (decimal)
  • conv=notrunc | don't truncate the output after the edit (which dd does by default)

One Josh looking out for another ;)

The printf+dd based solutions do not seem to work for writing out zeros. Here is a generic solution in python3 (included in all modern distros) which should work for all byte values...

#!/usr/bin/env python3
#file: set-byte

import sys

fileName = sys.argv[1]
offset = int(sys.argv[2], 0)
byte = int(sys.argv[3], 0)

with open(fileName, "r+b") as fh:
    fh.seek(offset)
    fh.write(bytes([byte]))

Usage...

set-byte eeprom_bad.bin 0x7D00 0
set-byte eeprom_bad.bin 1000 0xff

Note: This code can handle input numbers both in hex (prefixed by 0x) and dec (no prefix).

sinharaj

Here's a Bash function replaceByte, which takes the following parameters:

  • the name of the file,
  • an offset of the byte in the file to rewrite, and
  • the new value of the byte (a number).
#!/bin/bash

# param 1: file
# param 2: offset
# param 3: value
function replaceByte() {
    printf "$(printf '\\x%02X' $3)" | dd of="$1" bs=1 seek=$2 count=1 conv=notrunc &> /dev/null
}

# Usage:
# replaceByte 'thefile' $offset 95

xxd tool, which comes with vim (and thus is quite likely to be available) allows to hex dump a binary file and construct a new binary file from a modified hex dump.

Writing the same byte at two different positions in the same file with a one liner.

printf '\x00'| tee >(dd of=filename bs=1 count=1 seek=692 conv=notrunc status=none) \
    >(dd of=filename bs=1 count=1 seek=624 conv=notrunc status=none)

status=none very useful when you don't want any statistics out of dd.

If you don't need it to be scriptable, you could try the "hexedit" utility. It is available in many Linux distributions (if not installed by default, it can usually be found in the distro's package repository).

If your distro doesn't have it, you can build and install it from source.

Some alternatives:

Regarding Josh answer: In case you want to do it for a specific address

hexdump -C {file location}

with some hex value you might have tried to add 0x but it would fail :

dd: warning: ‘0x’ is a zero multiplier; use ‘00x’ if that is intended

You can achieve this by encapsulating it with $(()) that the terminal will translate as an int value :

mybinary={file location}
printf '\x31\xc0\xc3' | dd of=$mybinary bs=1 seek=$((0x100)) count=3 conv=notrunc 
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!