jumpserver/log_handler.py

85 lines
2.1 KiB
Python
Raw Normal View History

2015-02-05 10:53:57 +00:00
#!/usr/bin/python
2015-04-15 04:07:59 +00:00
# coding: utf-8
2015-02-05 10:53:57 +00:00
import os
2015-03-14 05:13:46 +00:00
import re
2015-02-05 10:53:57 +00:00
import time
2015-02-09 11:02:25 +00:00
import psutil
from datetime import datetime
2015-02-05 10:53:57 +00:00
os.environ['DJANGO_SETTINGS_MODULE'] = 'jumpserver.settings'
import django
django.setup()
from jlog.models import Log
2015-02-09 11:02:25 +00:00
def log_hanler(id):
log = Log.objects.get(id=id)
2015-04-18 10:04:01 +00:00
pattern = re.compile(r'([\[.*@.*\][\$#].* | mysql>.*])')
2015-02-05 10:53:57 +00:00
if log:
2015-02-09 11:02:25 +00:00
filename = log.log_path
2015-02-05 10:53:57 +00:00
if os.path.isfile(filename):
2015-03-14 05:13:46 +00:00
f_his = filename + '.his'
f1 = open(filename)
f2 = open(f_his, 'a')
lines = f1.readlines()
for line in lines[7:]:
match = pattern.match(line)
if match:
newline = re.sub('\[[A-Z]', '', line)
f2.write(newline)
f1.close()
f2.close()
2015-02-09 11:02:25 +00:00
log.log_finished = True
log.save()
2015-02-05 10:53:57 +00:00
def set_finish(id):
2015-02-09 11:02:25 +00:00
log = Log.objects.filter(id=id)
if log:
log.update(is_finished=1, end_time=datetime.now())
2015-02-05 10:53:57 +00:00
def kill_pid(pid):
try:
os.kill(pid, 9)
except OSError:
pass
def get_pids():
2015-02-09 11:02:25 +00:00
pids1, pids2 = [], []
pids1_obj = Log.objects.filter(is_finished=0)
pids2_obj = Log.objects.filter(is_finished=1, log_finished=0)
for pid_obj in pids1_obj:
pids1.append((pid_obj.id, pid_obj.pid, pid_obj.log_path, pid_obj.is_finished, pid_obj.log_finished, pid_obj.start_time))
for pid_obj in pids2_obj:
pids2.append(pid_obj.id)
2015-02-05 10:53:57 +00:00
2015-02-09 11:02:25 +00:00
return pids1, pids2
2015-02-05 10:53:57 +00:00
2015-02-09 11:02:25 +00:00
def run():
pids1, pids2 = get_pids()
for pid_id in pids2:
log_hanler(pid_id)
for pid_id, pid, log_path, is_finished, log_finished, start_time in pids1:
print pid_id, start_time, type(start_time)
try:
file_time = int(os.stat(log_path).st_ctime)
now_time = int(time.time())
if now_time - file_time > 18000:
if psutil.pid_exists(pid):
kill_pid(pid)
set_finish(pid_id)
log_hanler(pid_id)
except OSError:
pass
2015-02-05 10:53:57 +00:00
if __name__ == '__main__':
while True:
run()
2015-02-09 11:02:25 +00:00
time.sleep(5)