merge with dev

pull/26/head
ibuler 2015-12-19 17:30:21 +08:00
parent 7b792907d3
commit 39b7a7290f
10 changed files with 0 additions and 906 deletions

View File

@ -239,24 +239,6 @@ class Tty(object):
today_connect_log_dir = os.path.join(tty_log_dir, date_start) today_connect_log_dir = os.path.join(tty_log_dir, date_start)
log_file_path = os.path.join(today_connect_log_dir, '%s_%s_%s' % (self.username, self.asset_name, time_start)) log_file_path = os.path.join(today_connect_log_dir, '%s_%s_%s' % (self.username, self.asset_name, time_start))
<<<<<<< HEAD
def log_record(username, host):
"""Logging user command and output."""
connect_log_dir = os.path.join(LOG_DIR, 'connect')
timestamp_start = int(time.time())
today = time.strftime('%Y%m%d', time.localtime(timestamp_start))
time_now = time.strftime('%H%M%S', time.localtime(timestamp_start))
today_connect_log_dir = os.path.join(connect_log_dir, today)
log_filename = '%s_%s_%s.log' % (username, host, time_now)
log_file_path = os.path.join(today_connect_log_dir, log_filename)
dept_name = User.objects.get(username=username).dept.name
pid = os.getpid()
pts = os.popen("ps axu | grep %s | grep -v grep | awk '{ print $7 }'" % pid).read().strip()
ip_list = os.popen("who | grep %s | awk '{ print $5 }'" % pts).read().strip('()\n')
if not os.path.isdir(today_connect_log_dir):
=======
>>>>>>> dev
try: try:
mkdir(os.path.dirname(today_connect_log_dir), mode=0777) mkdir(os.path.dirname(today_connect_log_dir), mode=0777)
mkdir(today_connect_log_dir, mode=0777) mkdir(today_connect_log_dir, mode=0777)

View File

@ -84,13 +84,6 @@ def log_kill(request):
log = Log.objects.filter(pid=pid) log = Log.objects.filter(pid=pid)
if log: if log:
log = log[0] log = log[0]
<<<<<<< HEAD
dept_name = log.dept_name
deptname = get_session_user_info(request)[4]
if is_group_admin(request) and dept_name != deptname:
return httperror(request, u'Kill失败, 您无权操作!')
=======
>>>>>>> dev
try: try:
os.kill(int(pid), 9) os.kill(int(pid), 9)
except OSError: except OSError:

View File

@ -182,107 +182,6 @@ def perm_rule_edit(request):
asset_groups_select = request.POST.getlist('asset_group', []) asset_groups_select = request.POST.getlist('asset_group', [])
roles_select = request.POST.getlist('role', []) roles_select = request.POST.getlist('role', [])
<<<<<<< HEAD
@require_super_user
def perm_edit(request):
if request.method == 'GET':
header_title, path1, path2 = u'编辑授权', u'授权管理', u'授权编辑'
user_group_id = request.GET.get('id', '')
user_group = UserGroup.objects.filter(id=user_group_id)
if user_group:
user_group = user_group[0]
asset_groups_all = BisGroup.objects.all()
asset_groups_select = [perm.asset_group for perm in user_group.perm_set.all()]
asset_groups = [asset_group for asset_group in asset_groups_all if asset_group not in asset_groups_select]
else:
user_group_id = request.POST.get('user_group_id')
asset_group_id_list = request.POST.getlist('asset_groups_select')
perm_group_update(user_group_id, asset_group_id_list)
return HttpResponseRedirect('/jperm/perm_list/')
return render_to_response('jperm/perm_edit.html', locals(), context_instance=RequestContext(request))
@require_admin
def perm_edit_adm(request):
if request.method == 'GET':
header_title, path1, path2 = u'编辑授权', u'授权管理', u'授权编辑'
user_group_id = request.GET.get('id', '')
user_group = UserGroup.objects.filter(id=user_group_id)
user, dept = get_session_user_dept(request)
if user_group:
user_group = user_group[0]
asset_groups_all = dept.bisgroup_set.all()
asset_groups_select = [perm.asset_group for perm in user_group.perm_set.all()]
asset_groups = [asset_group for asset_group in asset_groups_all if asset_group not in asset_groups_select]
else:
user_group_id = request.POST.get('user_group_id')
asset_group_id_list = request.POST.getlist('asset_groups_select')
print user_group_id, asset_group_id_list
if not validate(request, user_group=[user_group_id], asset_group=asset_group_id_list):
return HttpResponseRedirect('/')
perm_group_update(user_group_id, asset_group_id_list)
return HttpResponseRedirect('/jperm/perm_list/')
return render_to_response('jperm/perm_edit.html', locals(), context_instance=RequestContext(request))
@require_admin
def perm_detail(request):
header_title, path1, path2 = u'授权管理', u'小组管理', u'授权详情'
group_id = request.GET.get('id')
user_group = UserGroup.objects.filter(id=group_id)
if user_group:
user_group = user_group[0]
users = user_group.user_set.all()
group_user_num = len(users)
perms = user_group.perm_set.all()
asset_groups = [perm.asset_group for perm in perms]
return render_to_response('jperm/perm_detail.html', locals(), context_instance=RequestContext(request))
@require_admin
def perm_del(request):
perm_id = request.GET.get('id')
perm = Perm.objects.filter(id=perm_id)
if perm:
perm = perm[0]
perm.delete()
return HttpResponseRedirect('/jperm/perm_list/')
@require_admin
def perm_asset_detail(request):
header_title, path1, path2 = u'用户授权主机', u'权限管理', u'用户主机详情'
user_id = request.GET.get('id')
user = User.objects.filter(id=user_id)
if user:
user = user[0]
assets_list = user_perm_asset_api(user.username)
return render_to_response('jperm/perm_asset_detail.html', locals(), context_instance=RequestContext(request))
def unicode2str(unicode_list):
return [str(i) for i in unicode_list]
def sudo_ldap_add(user_group, user_runas, asset_groups_select,
cmd_groups_select):
if LDAP_ENABLE:
ldap_conn = LDAPMgmt(LDAP_HOST_URL, LDAP_BASE_DN, LDAP_ROOT_DN, LDAP_ROOT_PW)
else:
return
assets = []
cmds = []
user_runas = user_runas.split(',')
if len(asset_groups_select) == 1 and asset_groups_select[0].name == 'ALL':
asset_all = True
else:
asset_all = False
for asset_group in asset_groups_select:
assets.extend(asset_group.asset_set.all())
=======
try: try:
if not rule_name or not roles_select: if not rule_name or not roles_select:
raise ServerError(u'系统用户和关联系统用户不能为空') raise ServerError(u'系统用户和关联系统用户不能为空')
@ -318,7 +217,6 @@ def sudo_ldap_add(user_group, user_runas, asset_groups_select,
rule.comment = rule_comment rule.comment = rule_comment
rule.save() rule.save()
msg = u"更新授权规则:%s成功" % rule.name msg = u"更新授权规则:%s成功" % rule.name
>>>>>>> dev
except ServerError, e: except ServerError, e:
error = e error = e
@ -389,66 +287,6 @@ def perm_role_add(request):
raise ServerError('已经存在该用户 %s' % name) raise ServerError('已经存在该用户 %s' % name)
default = get_object(Setting, name='default') default = get_object(Setting, name='default')
<<<<<<< HEAD
@require_admin
def cmd_add_adm(request):
header_title, path1, path2 = u'sudo命令添加', u'授权管理', u'命令组添加'
user, dept = get_session_user_dept(request)
if request.method == 'POST':
name = request.POST.get('name')
cmd = ','.join(request.POST.get('cmd').split('\n'))
comment = request.POST.get('comment')
try:
if CmdGroup.objects.filter(name=name):
error = '%s 命令组已存在'
raise ServerError(error)
except ServerError, e:
pass
else:
CmdGroup.objects.create(name=name, dept=dept, cmd=cmd, comment=comment)
return HttpResponseRedirect('/jperm/cmd_list/')
return HttpResponseRedirect('/jperm/cmd_list/')
return render_to_response('jperm/sudo_cmd_add.html', locals(), context_instance=RequestContext(request))
@require_admin
def cmd_edit(request):
header_title, path1, path2 = u'sudo命令修改', u'授权管理管理', u'命令组修改'
cmd_group_id = request.GET.get('id')
cmd_group = CmdGroup.objects.filter(id=cmd_group_id)
dept_all = DEPT.objects.all()
if cmd_group:
cmd_group = cmd_group[0]
cmd_group_id = cmd_group.id
dept_id = cmd_group.dept.id
name = cmd_group.name
cmd = '\n'.join(cmd_group.cmd.split(','))
comment = cmd_group.comment
if request.method == 'POST':
cmd_group_id = request.POST.get('cmd_group_id')
name = request.POST.get('name')
dept_id = request.POST.get('dept_id')
cmd = ','.join(request.POST.get('cmd').split('\n'))
comment = request.POST.get('comment')
cmd_group = CmdGroup.objects.filter(id=cmd_group_id)
dept = DEPT.objects.filter(id=dept_id)
try:
if not dept:
error = '没有该部门'
raise ServerError(error)
if not cmd_group:
error = '没有该命令组'
=======
if password: if password:
encrypt_pass = CRYPTOR.encrypt(password) encrypt_pass = CRYPTOR.encrypt(password)
else: else:
@ -465,7 +303,6 @@ def cmd_edit(request):
role.sudo = sudos_obj role.sudo = sudos_obj
msg = u"添加系统用户: %s" % name msg = u"添加系统用户: %s" % name
return HttpResponseRedirect(reverse('role_list')) return HttpResponseRedirect(reverse('role_list'))
>>>>>>> dev
except ServerError, e: except ServerError, e:
error = e error = e

View File

@ -17,13 +17,7 @@ web_socket_host = 192.168.244.129:3000
mail_enable = 1 mail_enable = 1
email_host = smtp.qq.com email_host = smtp.qq.com
email_port = 25 email_port = 25
<<<<<<< HEAD
email_host_user = 1152704203@qq.com
email_host_password = Hudie117...
email_use_tls = False
=======
email_host_user = ibuler@qq.com email_host_user = ibuler@qq.com
email_host_password = Hudie117...qq email_host_password = Hudie117...qq
email_use_tls = True email_use_tls = True
>>>>>>> dev

View File

@ -25,91 +25,6 @@ from jumpserver.models import Setting
from django.http import HttpResponseRedirect from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response from django.shortcuts import render_to_response
from django.core.mail import send_mail from django.core.mail import send_mail
<<<<<<< HEAD
import json
BASE_DIR = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
CONF = ConfigParser()
CONF.read(os.path.join(BASE_DIR, 'jumpserver.conf'))
LOG_DIR = os.path.join(BASE_DIR, 'logs')
SSH_KEY_DIR = os.path.join(BASE_DIR, 'keys')
SERVER_KEY_DIR = os.path.join(SSH_KEY_DIR, 'server')
KEY = CONF.get('base', 'key')
LOGIN_NAME = getpass.getuser()
LDAP_ENABLE = CONF.getint('ldap', 'ldap_enable')
SEND_IP = CONF.get('base', 'ip')
SEND_PORT = CONF.get('base', 'port')
MAIL_FROM = CONF.get('mail', 'email_host_user')
class LDAPMgmt():
def __init__(self,
host_url,
base_dn,
root_cn,
root_pw):
self.ldap_host = host_url
self.ldap_base_dn = base_dn
self.conn = ldap.initialize(host_url)
self.conn.set_option(ldap.OPT_REFERRALS, 0)
self.conn.protocol_version = ldap.VERSION3
self.conn.simple_bind_s(root_cn, root_pw)
def list(self, filter, scope=ldap.SCOPE_SUBTREE, attr=None):
result = {}
try:
ldap_result = self.conn.search_s(self.ldap_base_dn, scope, filter, attr)
for entry in ldap_result:
name, data = entry
for k, v in data.items():
print '%s: %s' % (k, v)
result[k] = v
return result
except ldap.LDAPError, e:
print e
def add(self, dn, attrs):
try:
ldif = modlist.addModlist(attrs)
self.conn.add_s(dn, ldif)
except ldap.LDAPError, e:
print e
def modify(self, dn, attrs):
try:
attr_s = []
for k, v in attrs.items():
attr_s.append((2, k, v))
self.conn.modify_s(dn, attr_s)
except ldap.LDAPError, e:
print e
def delete(self, dn):
try:
self.conn.delete_s(dn)
except ldap.LDAPError, e:
print e
def decrypt(self, text):
cryptor = AES.new(self.key, self.mode, b'0000000000000000')
try:
plain_text = cryptor.decrypt(a2b_hex(text))
except TypeError:
raise ServerError('Decrypt password error, TYpe error.')
return plain_text.rstrip('\0')
if LDAP_ENABLE:
LDAP_HOST_URL = CONF.get('ldap', 'host_url')
LDAP_BASE_DN = CONF.get('ldap', 'base_dn')
LDAP_ROOT_DN = CONF.get('ldap', 'root_dn')
LDAP_ROOT_PW = CONF.get('ldap', 'root_pw')
def md5_crypt(string):
return hashlib.new("md5", string).hexdigest()
=======
from django.core.urlresolvers import reverse from django.core.urlresolvers import reverse
@ -194,7 +109,6 @@ def chown(path, user, group=''):
os.chown(path, uid, gid) os.chown(path, uid, gid)
except KeyError: except KeyError:
pass pass
>>>>>>> dev
def page_list_return(total, current=1): def page_list_return(total, current=1):

View File

@ -273,23 +273,11 @@ def get_push_info(push_id, arg):
else: else:
return [] return []
<<<<<<< HEAD
@register.filter(name='sudo_cmd_count')
def sudo_cmd_count(cmd_group_id):
cmd_group = CmdGroup.objects.filter(id=cmd_group_id)
cmds = []
if cmd_group:
cmd_group = cmd_group[0]
return len(set(cmd_group.cmd.split(',')))
else:
return 0
=======
@register.filter(name='get_cpu_core') @register.filter(name='get_cpu_core')
def get_cpu_core(cpu_info): def get_cpu_core(cpu_info):
cpu_core = cpu_info.split('* ')[1] if cpu_info and '*' in cpu_info else cpu_info cpu_core = cpu_info.split('* ')[1] if cpu_info and '*' in cpu_info else cpu_info
return cpu_core return cpu_core
>>>>>>> dev
@register.filter(name='get_disk_info') @register.filter(name='get_disk_info')

View File

@ -14,330 +14,7 @@ from jperm.perm_api import get_group_user_perm
MAIL_FROM = EMAIL_HOST_USER MAIL_FROM = EMAIL_HOST_USER
<<<<<<< HEAD
def gen_rand_pwd(num):
"""生成随机密码"""
seed = "1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
salt_list = []
for i in range(num):
salt_list.append(random.choice(seed))
salt = ''.join(salt_list)
return salt
class AddError(Exception):
pass
def gen_sha512(salt, password):
return crypt.crypt(password, '$6$%s$' % salt)
def group_add_user(group, user_id=None, username=None):
try:
if user_id:
user = User.objects.get(id=user_id)
else:
user = User.objects.get(username=username)
except ObjectDoesNotExist:
raise AddError('用户获取失败')
else:
group.user_set.add(user)
def db_add_group(**kwargs):
name = kwargs.get('name')
group = UserGroup.objects.filter(name=name)
users = kwargs.pop('users')
if group:
raise AddError(u'用户组 %s 已经存在' % name)
group = UserGroup(**kwargs)
group.save()
for user_id in users:
group_add_user(group, user_id)
def db_add_user(**kwargs):
groups_post = kwargs.pop('groups')
user = User(**kwargs)
user.save()
if groups_post:
group_select = []
for group_id in groups_post:
group = UserGroup.objects.filter(id=group_id)
group_select.extend(group)
user.group = group_select
return user
def db_update_user(**kwargs):
groups_post = kwargs.pop('groups')
user_id = kwargs.pop('user_id')
user = User.objects.filter(id=user_id)
if user:
user.update(**kwargs)
user = User.objects.get(id=user_id)
user.save()
if groups_post:
group_select = []
for group_id in groups_post:
group = UserGroup.objects.filter(id=group_id)
group_select.extend(group)
user.group = group_select
def db_del_user(username):
try:
user = User.objects.get(username=username)
user.delete()
except ObjectDoesNotExist:
pass
def gen_ssh_key(username, password=None, length=2048):
private_key_dir = os.path.join(BASE_DIR, 'keys/jumpserver/')
private_key_file = os.path.join(private_key_dir, username+".pem")
public_key_dir = '/home/%s/.ssh/' % username
public_key_file = os.path.join(public_key_dir, 'authorized_keys')
is_dir(private_key_dir)
is_dir(public_key_dir, username, mode=0700)
key = RSA.generate(length)
with open(private_key_file, 'w') as pri_f:
pri_f.write(key.exportKey('PEM', password))
os.chmod(private_key_file, 0600)
pub_key = key.publickey()
with open(public_key_file, 'w') as pub_f:
pub_f.write(pub_key.exportKey('OpenSSH'))
os.chmod(public_key_file, 0600)
bash('chown %s:%s %s' % (username, username, public_key_file))
def server_add_user(username, password, ssh_key_pwd):
bash("useradd '%s'; echo '%s' | passwd --stdin '%s'" % (username, password, username))
gen_ssh_key(username, ssh_key_pwd)
def server_del_user(username):
bash('userdel -r %s' % username)
def ldap_add_user(username, ldap_pwd):
if LDAP_ENABLE:
ldap_conn = LDAPMgmt(LDAP_HOST_URL, LDAP_BASE_DN, LDAP_ROOT_DN, LDAP_ROOT_PW)
else:
return
user_dn = "uid=%s,ou=People,%s" % (username, LDAP_BASE_DN)
password_sha512 = gen_sha512(gen_rand_pwd(6), ldap_pwd)
user = User.objects.filter(username=username)
if user:
user = user[0]
else:
raise AddError(u'用户 %s 不存在' % username)
user_attr = {'uid': [str(username)],
'cn': [str(username)],
'objectClass': ['account', 'posixAccount', 'top', 'shadowAccount'],
'userPassword': ['{crypt}%s' % password_sha512],
'shadowLastChange': ['16328'],
'shadowMin': ['0'],
'shadowMax': ['99999'],
'shadowWarning': ['7'],
'loginShell': ['/bin/bash'],
'uidNumber': [str(user.id)],
'gidNumber': [str(user.id)],
'homeDirectory': [str('/home/%s' % username)]}
group_dn = "cn=%s,ou=Group,%s" % (username, LDAP_BASE_DN)
group_attr = {'objectClass': ['posixGroup', 'top'],
'cn': [str(username)],
'userPassword': ['{crypt}x'],
'gidNumber': [str(user.id)]}
ldap_conn.add(user_dn, user_attr)
ldap_conn.add(group_dn, group_attr)
def ldap_del_user(username):
if LDAP_ENABLE:
ldap_conn = LDAPMgmt(LDAP_HOST_URL, LDAP_BASE_DN, LDAP_ROOT_DN, LDAP_ROOT_PW)
else:
return
user_dn = "uid=%s,ou=People,%s" % (username, LDAP_BASE_DN)
group_dn = "cn=%s,ou=Group,%s" % (username, LDAP_BASE_DN)
sudo_dn = 'cn=%s,ou=Sudoers,%s' % (username, LDAP_BASE_DN)
ldap_conn.delete(user_dn)
ldap_conn.delete(group_dn)
ldap_conn.delete(sudo_dn)
@require_super_user
def dept_add(request):
header_title, path1, path2 = '添加部门', '用户管理', '添加部门'
if request.method == 'POST':
name = request.POST.get('name', '')
comment = request.POST.get('comment', '')
try:
if not name:
raise AddError('部门名称不能为空')
if DEPT.objects.filter(name=name):
raise AddError(u'部门名称 %s 已存在' % name)
except AddError, e:
error = e
else:
DEPT(name=name, comment=comment).save()
msg = u'添加部门 %s 成功' % name
return render_to_response('juser/dept_add.html', locals(), context_instance=RequestContext(request))
@require_super_user
def dept_list(request):
header_title, path1, path2 = '查看部门', '用户管理', '查看部门'
keyword = request.GET.get('search')
if keyword:
contact_list = DEPT.objects.filter(Q(name__icontains=keyword) | Q(comment__icontains=keyword)).order_by('name')
else:
contact_list = DEPT.objects.all().order_by('id')
contact_list, p, contacts, page_range, current_page, show_first, show_end = pages(contact_list, request)
return render_to_response('juser/dept_list.html', locals(), context_instance=RequestContext(request))
@require_admin
def dept_list_adm(request):
header_title, path1, path2 = '查看部门', '用户管理', '查看部门'
user, dept = get_session_user_dept(request)
contact_list = [dept]
contact_list, p, contacts, page_range, current_page, show_first, show_end = pages(contact_list, request)
return render_to_response('juser/dept_list.html', locals(), context_instance=RequestContext(request))
def chg_role(request):
role = {'SU': 2, 'DA': 1, 'CU': 0}
user, dept = get_session_user_dept(request)
if request.session['role_id'] > 0:
request.session['role_id'] = 0
elif request.session['role_id'] == 0:
request.session['role_id'] = role.get(user.role, 0)
return HttpResponseRedirect('/')
@require_super_user
def dept_detail(request):
dept_id = request.GET.get('id', None)
if not dept_id:
return HttpResponseRedirect('/juser/dept_list/')
dept = DEPT.objects.filter(id=dept_id)
if dept:
dept = dept[0]
users = dept.user_set.all()
return render_to_response('juser/dept_detail.html', locals(), context_instance=RequestContext(request))
@require_super_user
def dept_del(request):
dept_id = request.GET.get('id', None)
if not dept_id or dept_id in ['1', '2']:
return HttpResponseRedirect('/juser/dept_list/')
dept = DEPT.objects.filter(id=dept_id)
if dept:
dept = dept[0]
dept.delete()
return HttpResponseRedirect('/juser/dept_list/')
def dept_member(dept_id):
dept = DEPT.objects.filter(id=dept_id)
if dept:
dept = dept[0]
return dept.user_set.all()
def dept_member_update(dept, users_id_list):
old_users = dept.user_set.all()
new_users = []
for user_id in users_id_list:
new_users.extend(User.objects.filter(id=user_id))
remove_user = [user for user in old_users if user not in new_users]
add_user = [user for user in new_users if user not in old_users]
for user in add_user:
user.dept = dept
user.save()
dept_default = DEPT.objects.get(id=2)
for user in remove_user:
user.dept = dept_default
user.save()
@require_super_user
def dept_del_ajax(request):
dept_ids = request.POST.get('dept_ids')
for dept_id in dept_ids.split(','):
if int(dept_id) > 2:
DEPT.objects.filter(id=dept_id).delete()
return HttpResponse("删除成功")
@require_super_user
def dept_edit(request):
header_title, path1, path2 = '部门编辑', '用户管理', '部门编辑'
if request.method == 'GET':
dept_id = request.GET.get('id', '')
if dept_id:
dept = DEPT.objects.filter(id=dept_id)
if dept:
dept = dept[0]
users = dept_member(dept_id)
users_all = User.objects.all()
users_other = [user for user in users_all if user not in users]
else:
error = 'id 错误'
else:
error = u'部门不存在'
else:
dept_id = request.POST.get('id', '')
name = request.POST.get('name', '')
users = request.POST.getlist('users_selected', [])
comment = request.POST.get('comment', '')
dept = DEPT.objects.filter(id=dept_id)
if dept:
dept.update(name=name, comment=comment)
dept_member_update(dept[0], users)
else:
error = '部门不存在'
return HttpResponseRedirect('/juser/dept_list/')
return render_to_response('juser/dept_edit.html', locals(), context_instance=RequestContext(request))
def dept_user_ajax(request):
dept_id = request.GET.get('id', '4')
if dept_id not in ['1', '2']:
dept = DEPT.objects.filter(id=dept_id)
if dept:
dept = dept[0]
users = dept.user_set.all()
else:
users = User.objects.all()
return render_to_response('juser/dept_user_ajax.html', locals())
@require_super_user
=======
@require_role(role='super') @require_role(role='super')
>>>>>>> dev
def group_add(request): def group_add(request):
""" """
group add view for route group add view for route

View File

@ -1,105 +0,0 @@
#!/usr/bin/python
# coding: utf-8
import os
import re
import time
import psutil
from datetime import datetime
os.environ['DJANGO_SETTINGS_MODULE'] = 'jumpserver.settings'
import django
#django.setup()
from jlog.models import Log
def log_hanler(id):
log = Log.objects.get(id=id)
pattern = re.compile(r'([\[.*@.*\][\$#].*)|(.*mysql>.*)')
if log:
filename = log.log_path
if os.path.isfile(filename):
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()
log.log_finished = True
log.save()
def set_finish(id):
log = Log.objects.filter(id=id)
if log:
log.update(is_finished=1, end_time=datetime.now())
def kill_pid(pid):
try:
os.kill(pid, 9)
except OSError:
pass
def get_pids():
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)
return pids1, pids2
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:
try:
file_time = int(os.stat(log_path).st_ctime)
now_time = int(time.time())
if now_time - file_time > 10800:
if psutil.pid_exists(pid):
kill_pid(pid)
set_finish(pid_id)
log_hanler(pid_id)
except OSError:
pass
#function erorcheck is added by Lin to resolve CPU filled issue 2015.08.24
def errorcheck():
f=os.popen("ps auxr | grep -v auxr|sed -n 2p")
a=f.read().strip()
f.close()
pid=0
try:
if a is not None:
b=a.split(" ")
if b[-1]=='/opt/jumpserver/connect.py' and b[-2]=='python' and b[-8]=='R' and int(b[-3].split(':')[0])>100:
for i,j in enumerate(b):
if i==0 or j=='':
continue
else:
pid=int(j)
break
kill_pid(pid)
except :
pass
if __name__ == '__main__':
while True:
run()
time.sleep(5)
errorcheck()

File diff suppressed because one or more lines are too long

View File

@ -1,170 +0,0 @@
{% extends 'base.html' %}
{% load mytags %}
{% block content %}
{% include 'nav_cat_bar.html' %}
<div class="wrapper wrapper-content animated fadeInRight">
<div class="row">
<div class="col-lg-4">
<div class="ibox float-e-margins">
<div class="ibox-title">
<h5>授权主机/组</h5>
<div class="ibox-tools">
<a class="collapse-link">
<i class="fa fa-chevron-up"></i>
</a>
<a class="dropdown-toggle" data-toggle="dropdown" href="#">
<i class="fa fa-wrench"></i>
</a>
<ul class="dropdown-menu dropdown-user">
<li><a href="#">Config option 1</a>
</li>
<li><a href="#">Config option 2</a>
</li>
</ul>
<a class="close-link">
<i class="fa fa-times"></i>
</a>
</div>
</div>
<div class="ibox-content ibox-heading">
<h3>用户</h3>
<small><i class="fa fa-map-marker"></i> 组下用户.</small>
</div>
<div class="ibox-content inspinia-timeline">
<div class="timeline-item">
<div class="row">
<div class="col-xs-3 date">
<i class="fa fa-users"></i>
<b>{{ user_group.name }}</b>
<br>
<small class="text-navy">共: {{ group_user_num }} 用户</small>
</div>
<div class="col-xs-7 content no-top-border">
<p class="m-b-xs"><strong>{{ user_group.comment }}</strong></p>
<p>
{% for user in users %}
{{ user.name }}<br>
{% endfor %}
</p>
<p></p>
</div>
</div>
</div>
{% if not users %}
(暂无)
{% endif %}
</div>
</div>
</div>
<div class="col-lg-4">
<div class="ibox float-e-margins">
<div class="ibox-title">
<h5>授权主机/组</h5>
<div class="ibox-tools">
<a class="collapse-link">
<i class="fa fa-chevron-up"></i>
</a>
<a class="dropdown-toggle" data-toggle="dropdown" href="#">
<i class="fa fa-wrench"></i>
</a>
<ul class="dropdown-menu dropdown-user">
<li><a href="#">Config option 1</a>
</li>
<li><a href="#">Config option 2</a>
</li>
</ul>
<a class="close-link">
<i class="fa fa-times"></i>
</a>
</div>
</div>
<div class="ibox-content ibox-heading">
<h3>授权主机/组</h3>
<small><i class="fa fa-map-marker"></i> 这里包含了sudo授权所有的主机组和组下的主机.</small>
</div>
<div class="ibox-content inspinia-timeline">
{% for group in asset_groups %}
<div class="timeline-item">
<div class="row">
<div class="col-xs-3 date">
<i class="fa fa-repeat"></i>
<b>{{ group.name }}</b>
<br>
<small class="text-navy">共: {{ group | group_asset_list_count }}台</small>
</div>
<div class="col-xs-7 content no-top-border">
<p class="m-b-xs"><strong>{{ group.comment }}</strong></p>
<p>
{% for asset in group|group_asset_list %}
{{ asset.ip }}<br>
{% endfor %}
</p>
<p></p>
</div>
</div>
</div>
{% endfor %}
{% if not asset_groups %}
(暂无)
{% endif %}
</div>
</div>
</div>
<div class="col-lg-4">
<div class="ibox float-e-margins">
<div class="ibox-title">
<h5>授权命令/组</h5>
<div class="ibox-tools">
<a class="collapse-link">
<i class="fa fa-chevron-up"></i>
</a>
<a class="dropdown-toggle" data-toggle="dropdown" href="#">
<i class="fa fa-wrench"></i>
</a>
<ul class="dropdown-menu dropdown-user">
<li><a href="#">Config option 1</a>
</li>
<li><a href="#">Config option 2</a>
</li>
</ul>
<a class="close-link">
<i class="fa fa-times"></i>
</a>
</div>
</div>
<div class="ibox-content inspinia-timeline">
{% for cmd_group in cmd_groups %}
<div class="timeline-item">
<div class="row">
<div class="col-xs-3 date">
<i class="fa fa-linux"></i>
<b>{{ cmd_group.name }}</b>
<br>
<small class="text-navy">共: {{ cmd_group.id | sudo_cmd_count }} 个</small>
</div>
<div class="col-xs-7 content no-top-border">
<p class="m-b-xs"><strong>{{ group.comment }}</strong></p>
<p>
{% for cmd in cmd_group|cmd_group_split %}
{{ cmd }}<br>
{% endfor %}
</p>
<p></p>
</div>
</div>
</div>
{% endfor %}
{% if not cmd_groups %}
(暂无)
{% endif %}
</div>
</div>
</div>
</div>
</div>
{% endblock %}