jumpserver/log_handler.py

77 lines
2.0 KiB
Python
Raw Normal View History

2015-02-05 10:53:57 +00:00
#!/usr/bin/python
#coding: utf-8
import os
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-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):
ret1 = os.system('cat %s | grep "DateTime" > %s.his' % (filename, filename))
ret2 = os.system('cat %s | grep "\[.*@.*\][\$\#]" >> %s.his' % (filename, filename))
ret3 = os.system('cat %s | grep "EndTime" >> %s.his' % (filename, filename))
if (ret1 + ret2 + ret3) == 0:
print 'Handler %s ok.' % filename
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)