a very simple and quick to copy and paste cli hex editor - python

A very simple thing but maybe somebody will find this useful.
I had a need for a simple hex editor, so I wrote this:

 #!/usr/bin/env python
import sys
"""
a very simple cli hex file editor
"""
if len(sys.argv) < 3:
  print "usage: %s filename hex_offset " % (sys.argv[0])
  sys.exit(0)
fd = open(sys.argv[1],"rw+")
fd.seek(int(sys.argv[2],16))
print "offset:0x%s char:%s" % (sys.argv[2], hex(ord(fd.read(1))))
fd.seek(int(sys.argv[2],16))
if len(sys.argv) > 3:
  fd.write(chr(int(sys.argv[3],16)))
  fd.seek(int(sys.argv[2],16))
  print "offset:0x%s char:%s" % (sys.argv[2], hex(ord(fd.read(1))))
fd.close()

Usage is simple, it takes three arguments (third one is optional), first is the path to the file you want to edit, second is offset in hex from the beginning of that file. If you do not provide the third argument then only a value under given offset is printed to the screen (nothing is changed), if you provide third value (in hex) then this value is written under that offset.

Example:
> dd if=/dev/urandom of=test_file.dat count=1 bs=32
1+0 records in
1+0 records out
32 bytes (32 B) copied, 0.0002849 s, 112 kB/s 
> cat test_file.dat | xxd
00000000: 4721 d36c 0335 572f cb51 323d d4ec bc3e  G!.l.5W/.Q2=...>
00000010: 6e00 905a c484 3fbf ca6e d202 f0ec bc18  n..Z..?..n...... 
> ./edit_file.py test_file.dat 10
offset:0x10 char:0x6e 
> ./edit_file.py test_file.dat 10 ff
offset:0x10 char:0x6e
offset:0x10 char:0xff 
> cat test_file.dat | xxd
00000000: 4721 d36c 0335 572f cb51 323d d4ec bc3e  G!.l.5W/.Q2=...>
00000010: ff00 905a c484 3fbf ca6e d202 f0ec bc18  ...Z..?..n......

EDIT (added 2016/01/08):

A bit improved (and just slightly bigger) version that can be found here, it is able to also handle ranges.

Example:

> cat test_file.dat | xxd
00000000: 4721 d36c 0335 572f cb51 323d d4ec bc3e  G!.l.5W/.Q2=...>
00000010: 6e00 905a c484 3fbf ca6e d202 f0ec bc18  n..Z..?..n......


> hedit.py test_file.dat 10-4
offset:0x10 6e00905a


> hedit.py test_file.dat 10-4 abcdef
offset:0x10 6e00905a
offset:0x10 abcdef5a


> cat test_file.dat | xxd
00000000: 4721 d36c 0335 572f cb51 323d d4ec bc3e  G!.l.5W/.Q2=...>
00000010: abcd ef5a c484 3fbf ca6e d202 f0ec bc18  ...Z..?..n......


A very simple WebSocket client - RFC 6455

A while ago I had a need for a simple WebSocket (RFC 6455) client, nothing fancy, just enough to verify few things are working correctly on a sever. All python libraries I could find were a bit on the heavy side, so I wrote a simple WebSocket client class from scratch. I'm sure it doesn't support everything but for me this is good enough.


Code is here, it can be use either standalone or as a module. By default is takes input from stdin and writes to stdout. It is asynchronous.


 > ./websocket.py
usage: ./websocket.py target port path


target is the IP or a hostname to which we want to connect
port is a TCP port on which the service is listening
path is the WebSocket path