jumpserver/jlog/log_api.py

78 lines
2.2 KiB
Python
Raw Normal View History

2015-10-26 14:17:16 +00:00
# coding: utf-8
from argparse import ArgumentParser, FileType
from contextlib import closing
2015-11-28 13:13:44 +00:00
from io import open as copen
2015-10-26 14:17:16 +00:00
from json import dumps
from math import ceil
2015-11-27 09:53:11 +00:00
import re
2015-10-26 14:17:16 +00:00
from os.path import basename, dirname, exists, join
from struct import unpack
from subprocess import Popen
from sys import platform, prefix, stderr
from tempfile import NamedTemporaryFile
from jinja2 import FileSystemLoader, Template
from jinja2.environment import Environment
from jumpserver.api import BASE_DIR
DEFAULT_TEMPLATE = join(BASE_DIR, 'templates', 'jlog', 'static.jinja2')
2015-11-27 09:53:11 +00:00
rz_pat = re.compile(r'\x18B\w+\r\x8a(\x11)?')
2015-10-26 14:17:16 +00:00
def escapeString(string):
2015-11-27 09:53:11 +00:00
string = rz_pat.sub('', string)
try:
string = string.encode('unicode_escape').decode('utf-8', 'ignore')
except (UnicodeEncodeError, UnicodeDecodeError):
string = string.decode('utf-8', 'ignore')
2015-10-26 14:17:16 +00:00
string = string.replace("'", "\\'")
string = '\'' + string + '\''
return string
def getTiming(timef):
timing = None
with closing(timef):
timing = [l.strip().split(' ') for l in timef]
timing = [(int(ceil(float(r[0]) * 1000)), int(r[1])) for r in timing]
return timing
def scriptToJSON(scriptf, timing=None):
ret = []
with closing(scriptf):
2015-11-29 03:33:19 +00:00
scriptf.readline() # ignore first header line from script file
2015-10-26 14:17:16 +00:00
offset = 0
for t in timing:
2015-11-26 05:21:05 +00:00
dt = scriptf.read(t[1])
data = escapeString(dt)
2015-11-29 03:33:19 +00:00
# print ('###### (%s, %s)' % (t[1], repr(data)))
2015-10-26 14:17:16 +00:00
offset += t[0]
ret.append((data, offset))
return dumps(ret)
2015-10-27 12:25:18 +00:00
def renderTemplate(script_path, time_file_path, dimensions=(24, 80), templatename=DEFAULT_TEMPLATE):
2015-11-28 13:13:44 +00:00
with copen(script_path, encoding='utf-8', errors='replace', newline='\r\n') as scriptf:
# with open(script_path) as scriptf:
2015-10-26 14:17:16 +00:00
with open(time_file_path) as timef:
timing = getTiming(timef)
json = scriptToJSON(scriptf, timing)
fsl = FileSystemLoader(dirname(templatename), 'utf-8')
e = Environment()
e.loader = fsl
templatename = basename(templatename)
rendered = e.get_template(templatename).render(json=json,
dimensions=dimensions)
return rendered