Skip to content

Instantly share code, notes, and snippets.

@ph1ee
Last active January 18, 2019 04:45
Show Gist options
  • Select an option

  • Save ph1ee/b06a3a1e35a08b41c8ae9fc0b74aeb26 to your computer and use it in GitHub Desktop.

Select an option

Save ph1ee/b06a3a1e35a08b41c8ae9fc0b74aeb26 to your computer and use it in GitHub Desktop.
unhexlify socat -x -v format
#!/usr/bin/env python3
import sys
import os
from codecs import decode
from re import compile as regex
from enum import Enum
DEBUG = True if os.getenv("DEBUG") else False
class State(Enum):
END = '--'
GT = '> '
LT = '< '
# 20:35:44.410594
pattern = regex(r'(\d+/\d+/\d+)\s+(\d+:\d+:\d+\.\d+)')
class SocatXv(object):
def __init__(self):
self.reset()
def reset(self):
self.last = State.END
self.curr = State.END
self.iobuf = {State.GT: bytearray(), State.LT: bytearray()}
self.timestamp = {State.GT: "", State.LT: ""}
def print(self, state):
inout = "{}{}".format(self.timestamp[state] if DEBUG else "", state.value if DEBUG else "")
print("{}{}".format(inout, decode(self.iobuf[state], "hex").decode()))
self.iobuf[state] = bytearray()
def unhexlify(self, fp):
for line in fp: # for each line
if self.curr == State.END:
if line.startswith(State.GT.value):
if self.last == State.LT:
self.print(self.last)
self.curr = State.GT
self.timestamp[self.curr] = pattern.search(line).group(2)
elif line.startswith(State.LT.value):
if self.last == State.GT:
self.print(self.last)
self.curr = State.LT
self.timestamp[self.curr] = pattern.search(line).group(2)
else:
raise Exception(line)
elif self.curr == State.GT or self.curr == State.LT:
if line.startswith(State.END.value):
self.last = self.curr
self.curr = State.END
else:
hexstr = "".join(line[1: 48].split()).encode()
self.iobuf[self.curr].extend(hexstr)
if self.curr != State.END and self.iobuf[self.curr]:
self.print(self.curr)
if __name__ == "__main__":
fp = sys.stdin
if len(sys.argv) > 1 and os.path.isfile(sys.argv[1]):
fp = open(sys.argv[1], "r")
socatxv = SocatXv()
sys.exit(socatxv.unhexlify(fp))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment