Last active
January 18, 2019 04:45
-
-
Save ph1ee/b06a3a1e35a08b41c8ae9fc0b74aeb26 to your computer and use it in GitHub Desktop.
unhexlify socat -x -v format
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/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