disuse pyinotify, use TermLogRecord to record the log and monitor

pull/167/head
liuzheng712 2016-03-27 11:11:50 +08:00
parent 5e329f51a4
commit dc5751951e
3 changed files with 72 additions and 41 deletions

View File

@ -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)

View File

@ -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 = [

View File

@ -109,7 +109,7 @@
<td id="remote_ip" class="text-center"> {{ post.remote_ip }} </td>
<td class="text-center"> {{ post.login_type }} </td>
<td class="text-center"><a href="{% url 'log_history' %}?id={{ post.id }}" class="log_command"> 统计 </a></td>
<td class="text-center"><a class="monitor" file_path="{{ post.log_path }}"> 监控 </a></td>
<td class="text-center"><a class="monitor" monitor-id="{{ post.id }}"> 监控 </a></td>
<td class="text-center"><input type="button" id="cut" class="btn btn-danger btn-xs" name="cut" value="阻断" onclick='cut("{{ post.pid }}", "{{ post.login_type }}")' /></td>
<td class="text-center" id="start_time"> {{ post.start_time|date:"Y-m-d H:i:s" }} </td>
</tr>
@ -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');
};