From dc5751951e6a78f6cc057d37392a07d39c63fc3f Mon Sep 17 00:00:00 2001 From: liuzheng712 Date: Sun, 27 Mar 2016 11:11:50 +0800 Subject: [PATCH] disuse pyinotify, use TermLogRecord to record the log and monitor --- jlog/views.py | 18 +++++-- run_server.py | 87 +++++++++++++++++++++------------- templates/jlog/log_online.html | 8 ++-- 3 files changed, 72 insertions(+), 41 deletions(-) diff --git a/jlog/views.py b/jlog/views.py index 1386fd21f..579addf2f 100644 --- a/jlog/views.py +++ b/jlog/views.py @@ -7,7 +7,7 @@ from jperm.perm_api import user_have_perm from django.http import HttpResponseNotFound from jlog.log_api import renderTemplate -from jlog.models import Log, ExecLog, FileLog,TermLog +from jlog.models import Log, ExecLog, FileLog, TermLog from jumpserver.settings import LOG_DIR import zipfile import json @@ -137,13 +137,14 @@ def log_record(request): log_id = request.REQUEST.get('id', None) if log_id: TermL = TermLogRecorder(request.user) - log = TermLog.objects.get(id=int(log_id)) - return HttpResponse(TermL.load_full_log(log.filename)) + log = Log.objects.get(id=int(log_id)) + return HttpResponse(TermL.load_full_log(filename=log.log_path)) else: return HttpResponse("ERROR") else: return HttpResponse("ERROR METHOD!") + @require_role('admin') def log_detail(request, offset): log_id = request.GET.get('id') @@ -186,10 +187,13 @@ class TermLogRecorder(object): recoder.load_history(filename) # will only get the command history list recoder.share_to(filename,user=UserObject) # or recoder.share_to(filename,uid=UserID). will share this commands to someone recoder.unshare_to(filename,user=UserObject) # or recoder.unshare_to(filename,uid=UserID). will unshare this commands to someone + recoder.setid(id) # registered this term with an id, for monitor """ + loglist = dict() def __init__(self, user=None, uid=None): self.log = {} + self.id = 0 if isinstance(user, User): self.user = user elif uid: @@ -223,6 +227,9 @@ class TermLogRecorder(object): self.CMD[str(time.time())] = self.commands[-1] self._screen.reset() + def setid(self, id): + TermLogRecorder.loglist[str(id)] = self + def write(self, msg): if self.recoder and (not self._in_vim): if self.commands.__len__() == 0: @@ -240,6 +247,10 @@ class TermLogRecorder(object): self._screen.reset() else: self._command() + try: + self.write_message(msg) + except: + pass # print "<<<<<<<<<<<<<<<<" # print self.commands # print self.CMD @@ -249,6 +260,7 @@ class TermLogRecorder(object): def save(self, path=LOG_DIR): date = datetime.datetime.now().strftime('%Y%m%d') filename = str(uuid.uuid4()) + self.filename = filename filepath = os.path.join(path, 'tty', date, filename + '.zip') if not os.path.isdir(os.path.join(path, 'tty', date)): os.makedirs(os.path.join(path, 'tty', date), mode=0777) diff --git a/run_server.py b/run_server.py index f5693ef1d..d44fff2f9 100755 --- a/run_server.py +++ b/run_server.py @@ -22,7 +22,7 @@ import tornado.httpclient from tornado.websocket import WebSocketClosedError from tornado.options import define, options -from pyinotify import WatchManager, ProcessEvent, IN_DELETE, IN_CREATE, IN_MODIFY, AsyncNotifier +# from pyinotify import WatchManager, ProcessEvent, IN_DELETE, IN_CREATE, IN_MODIFY, AsyncNotifier import select from connect import Tty, User, Asset, PermRole, logger, get_object, gen_resource @@ -101,41 +101,41 @@ class MyThread(threading.Thread): pass -class EventHandler(ProcessEvent): - def __init__(self, client=None): - self.client = client - - def process_IN_MODIFY(self, event): - self.client.write_message(f.read()) +# class EventHandler(ProcessEvent): +# def __init__(self, client=None): +# self.client = client +# +# def process_IN_MODIFY(self, event): +# self.client.write_message(f.read()) +# +# +# def file_monitor(path='.', client=None): +# wm = WatchManager() +# mask = IN_DELETE | IN_CREATE | IN_MODIFY +# notifier = AsyncNotifier(wm, EventHandler(client)) +# wm.add_watch(path, mask, auto_add=True, rec=True) +# if not os.path.isfile(path): +# logger.debug("File %s does not exist." % path) +# sys.exit(3) +# else: +# logger.debug("Now starting monitor file %s." % path) +# global f +# f = open(path, 'r') +# st_size = os.stat(path)[6] +# f.seek(st_size) +# +# while True: +# try: +# notifier.process_events() +# if notifier.check_events(): +# notifier.read_events() +# except KeyboardInterrupt: +# print "keyboard Interrupt." +# notifier.stop() +# break -def file_monitor(path='.', client=None): - wm = WatchManager() - mask = IN_DELETE | IN_CREATE | IN_MODIFY - notifier = AsyncNotifier(wm, EventHandler(client)) - wm.add_watch(path, mask, auto_add=True, rec=True) - if not os.path.isfile(path): - logger.debug("File %s does not exist." % path) - sys.exit(3) - else: - logger.debug("Now starting monitor file %s." % path) - global f - f = open(path, 'r') - st_size = os.stat(path)[6] - f.seek(st_size) - - while True: - try: - notifier.process_events() - if notifier.check_events(): - notifier.read_events() - except KeyboardInterrupt: - print "keyboard Interrupt." - notifier.stop() - break - - -class MonitorHandler(tornado.websocket.WebSocketHandler): +class MonitorHandler_old(tornado.websocket.WebSocketHandler): clients = [] threads = [] @@ -409,6 +409,7 @@ class WebTerminalHandler(tornado.websocket.WebSocketHandler): def forward_outbound(self): self.log_file_f, self.log_time_f, self.log = self.term.get_log() self.id = self.log.id + self.termlog.setid(self.id) try: data = '' pre_timestamp = time.time() @@ -440,6 +441,24 @@ class WebTerminalHandler(tornado.websocket.WebSocketHandler): pass +class MonitorHandler(WebTerminalHandler): + @django_request_support + @require_auth('user') + def open(self): + try: + self.returnlog = TermLogRecorder.loglist[int(self.get_argument('id'))] + self.returnlog.write_message = self.write_message + except: + self.write_message('Log is None') + self.close() + + def on_message(self, message): + pass + + def on_close(self): + self.close() + + class Application(tornado.web.Application): def __init__(self): handlers = [ diff --git a/templates/jlog/log_online.html b/templates/jlog/log_online.html index c7724451e..d32e33b53 100644 --- a/templates/jlog/log_online.html +++ b/templates/jlog/log_online.html @@ -109,7 +109,7 @@ {{ post.remote_ip }} {{ post.login_type }} 统计 - 监控 + 监控 {{ post.start_time|date:"Y-m-d H:i:s" }} @@ -137,8 +137,8 @@ } var endpoint = protocol + document.URL.match(RegExp('//(.*?)/'))[1] + '/ws/monitor'; - var file_path = obj.attr('file_path'); - var socket = new WebSocket(endpoint + '?file_path=' + file_path); + var monitorid = obj.attr('monitor-id'); + var socket = new WebSocket(endpoint + '?id=' + monitorid); var term = new Terminal({ cols: 80, @@ -153,7 +153,7 @@ term.resize(80, 24); socket.onopen = function(evt){ - socket.send('hello'); +{# socket.send('hello');#} term.write('~.~ Connect WebSocket Success.~.~ \r\n'); };