lost playboo_run

pull/26/head
广宏伟 2015-10-21 20:44:28 +08:00
parent fe1f825fdf
commit 40d00f7cbd
4 changed files with 65 additions and 263 deletions

View File

@ -7,5 +7,7 @@ from jasset.models import Asset, AssetGroup
class PermLog(models.Model):
datetime = models.DateTimeField(auto_now_add=True)
result = models.CharField(max_length=1000, null=True, blank=True, default='')
is_finished = models.BooleanField(default=False)
action = models.CharField(max_length=100, null=True, blank=True, default='')
results = models.CharField(max_length=1000, null=True, blank=True, default='')
is_success = models.BooleanField(default=False)
is_finish = models.BooleanField(default=False)

View File

@ -6,9 +6,10 @@ import uuid
import re
from ansible.playbook import PlayBook
from ansible import callbacks, utils
from jumpserver.tasks import playbook_run, add
from jumpserver.tasks import playbook_run
from jumpserver.models import Setting
from jperm.models import PermLog
def get_object_list(model, id_list):
@ -64,38 +65,21 @@ def perm_user_api(perm_info):
'new': {'users': [],
'assets': []}}
"""
log = PermLog(action=perm_info.get('action', ''))
try:
new_users = perm_info.get('new', {}).get('users', [])
new_assets = perm_info.get('new', {}).get('assets',[])
new_assets = perm_info.get('new', {}).get('assets', [])
del_users = perm_info.get('del', {}).get('users', [])
del_assets = perm_info.get('del', {}).get('assets', [])
print new_users, new_assets
except IndexError:
raise ServerError("Error: function perm_user_api传入参数错误")
# 检查传入的是字符串还是对象
check_users = new_users + del_users
try:
if isinstance(check_users[0], str):
var_type = 'str'
else:
var_type = 'obj'
except IndexError:
raise ServerError("Error: function perm_user_api传入参数错误")
try:
if var_type == 'str':
new_ip = new_assets
del_ip = del_assets
new_username = new_users
del_username = del_users
else:
new_ip = [asset.ip for asset in new_assets if isinstance(asset, Asset)]
del_ip = [asset.ip for asset in del_assets if isinstance(asset, Asset)]
new_username = [user.username for user in new_users if isinstance(user, User)]
del_username = [user.username for user in del_users if isinstance(user, User)]
new_ip = [asset.ip for asset in new_assets if isinstance(asset, Asset)]
del_ip = [asset.ip for asset in del_assets if isinstance(asset, Asset)]
new_username = [user.username for user in new_users if isinstance(user, User)]
del_username = [user.username for user in del_users if isinstance(user, User)]
except IndexError:
raise ServerError("Error: function perm_user_api传入参数类型错误")
@ -114,11 +98,20 @@ def perm_user_api(perm_info):
settings = get_object(Setting, name='default')
results = playbook_run(inventory, playbook, settings)
if not results.get('failed', 1) and not results.get('unreachable', ''):
is_success = True
else:
is_success = False
log.results = results
log.is_finish = True
log.is_success = is_success
log.save()
return results
def user_group_permed(user_group):
assets = user_group.asset_set.all()
assets = user_group.asset.all()
asset_groups = user_group.asset_group.all()
for asset_group in asset_groups:
@ -130,7 +123,7 @@ def user_group_permed(user_group):
def user_permed(user):
asset_groups = []
assets = []
user_groups = user.user_group.all()
user_groups = user.group.all()
asset_groups.extend(user.asset_group.all())
assets.extend(user.asset.all())
@ -213,7 +206,7 @@ def _public_perm_api(info):
new_assets.extend(user_group_permed(user_group).get('assets', []))
perm_info = {
'new': {'users': [user], 'assets': new_assets}
'new': {'action': 'new user: ' + user.name, 'users': [user], 'assets': new_assets}
}
elif info.get('type') == 'edit_user':
new_assets = []
@ -229,6 +222,7 @@ def _public_perm_api(info):
del_assets.extend((user_group_permed(user_group).get('assets', [])))
perm_info = {
'action': 'edit user: ' + user.name,
'del': {'users': [user], 'assets': del_assets},
'new': {'users': [user], 'assets': new_assets}
}
@ -237,7 +231,7 @@ def _public_perm_api(info):
user = info.get('user')
del_assets = user_permed(user).get('assets', [])
perm_info = {
'del': {'users': [user], 'assets': del_assets},
'action': 'del user: ' + user.name, 'del': {'users': [user], 'assets': del_assets},
}
elif info.get('type') == 'edit_user_group':
@ -247,18 +241,32 @@ def _public_perm_api(info):
assets = user_group_permed(user_group).get('assets', [])
perm_info = {
'action': 'edit user group: ' + user_group.name,
'new': {'users': new_users, 'assets': assets},
'del': {'users': del_users, 'assets': assets}
}
elif info.get('type') == 'del_user_group':
assets = []
user_groups = info.get('group', [])
del_users = [user_group.user_set.all() for user_group in user_groups]
for user_group in user_groups:
assets.extend(user_group_permed(user_group).get('assets', []))
user_group = info.get('group', [])
del_users = user_group.user_set.all()
assets = user_group_permed(user_group).get('assets', [])
perm_info = {
'action': "del user group: " + user_group.name, 'del': {'users': del_users, 'assets': assets}
}
else:
return
try:
results = perm_user_api(perm_info) # 通过API授权或回收
except ServerError, e:
return e
else:
return results
perm_info = {}

File diff suppressed because one or more lines are too long

View File

@ -11,6 +11,7 @@ from django.template import RequestContext
from django.db.models import ObjectDoesNotExist
from juser.user_api import *
from jperm.perm_api import _public_perm_api, perm_user_api, user_permed
def chg_role(request):
@ -89,31 +90,6 @@ def group_del(request):
return HttpResponse('删除成功')
# @require_role(role='admin')
# def group_list_adm(request):
# header_title, path1, path2 = '查看部门小组', '用户管理', '查看小组'
# keyword = request.GET.get('search', '')
# did = request.GET.get('did', '')
# user, dept = get_session_user_dept(request)
# contact_list = dept.usergroup_set.all().order_by('name')
#
# if keyword:
# contact_list = contact_list.filter(Q(name__icontains=keyword) | Q(comment__icontains=keyword))
#
# contact_list, p, contacts, page_range, current_page, show_first, show_end = pages(contact_list, request)
# return render_to_response('juser/group_list.html', locals(), context_instance=RequestContext(request))
#
# @require_role(role='admin')
# def group_detail(request):
# group_id = request.GET.get('id', None)
# if not group_id:
# return HttpResponseRedirect('/')
# group = UserGroup.objects.get(id=group_id)
# users = group.user_set.all()
# return render_to_response('juser/group_detail.html', locals(), context_instance=RequestContext(request))
@require_role(role='super')
def group_edit(request):
error = ''
@ -165,54 +141,6 @@ def group_edit(request):
return my_render('juser/group_edit.html', locals(), request)
# @require_role(role='admin')
# def group_edit_adm(request):
# error = ''
# msg = ''
# header_title, path1, path2 = '修改小组信息', '用户管理', '编辑小组'
# user, dept = get_session_user_dept(request)
# if request.method == 'GET':
# group_id = request.GET.get('id', '')
# if not validate(request, user_group=[group_id]):
# return HttpResponseRedirect('/juser/group_list/')
# group = UserGroup.objects.filter(id=group_id)
# if group:
# group = group[0]
# users_all = dept.user_set.all()
# users_selected = group.user_set.all()
# users = [user for user in users_all if user not in users_selected]
#
# return render_to_response('juser/group_edit.html', locals(), context_instance=RequestContext(request))
# else:
# group_id = request.POST.get('group_id', '')
# group_name = request.POST.get('group_name', '')
# comment = request.POST.get('comment', '')
# users_selected = request.POST.getlist('users_selected')
#
# users = []
# try:
# if not validate(request, user=users_selected):
# raise ServerError(u'右侧非部门用户')
#
# if not validate(request, user_group=[group_id]):
# raise ServerError(u'没有权限修改本组')
#
# for user_id in users_selected:
# users.extend(User.objects.filter(id=user_id))
#
# user_group = UserGroup.objects.filter(id=group_id)
# if user_group:
# user_group.update(name=group_name, comment=comment, dept=dept)
# user_group = user_group[0]
# user_group.user_set.clear()
# user_group.user_set = users
#
# except ServerError, e:
# error = e
#
# return HttpResponseRedirect('/juser/group_list/')
@require_role(role='super')
def user_add(request):
error = ''
@ -257,11 +185,20 @@ def user_add(request):
is_active=is_active,
date_joined=datetime.datetime.now())
server_add_user(username, password, ssh_key_pwd, ssh_key_login_need)
except Exception, e:
user = get_object(User, username=username)
if groups:
user_groups = []
for user_group_id in groups:
user_groups.extend(UserGroup.objects.filter(id=user_group_id))
print user_groups
results = _public_perm_api({'type': 'new_user', 'user': user, 'group': user_groups})
print results
except IndexError, e:
error = u'添加用户 %s 失败 %s ' % (username, e)
try:
db_del_user(username)
server_del_user(username)
_public_perm_api({'type': 'del_user', 'user': user, 'group': user_groups})
except Exception:
pass
else:
@ -271,78 +208,6 @@ def user_add(request):
return my_render('juser/user_add.html', locals(), request)
# @require_role(role='admin')
# def user_add_adm(request):
# error = ''
# msg = ''
# header_title, path1, path2 = '添加用户', '用户管理', '添加用户'
# user, dept = get_session_user_dept(request)
# group_all = dept.usergroup_set.all()
#
# if request.method == 'POST':
# username = request.POST.get('username', '')
# password = PyCrypt.gen_rand_pwd(16)
# name = request.POST.get('name', '')
# email = request.POST.get('email', '')
# groups = request.POST.getlist('groups', [])
# ssh_key_pwd = PyCrypt.gen_rand_pwd(16)
# is_active = True if request.POST.get('is_active', '1') == '1' else False
# ldap_pwd = PyCrypt.gen_rand_pwd(16)
#
# try:
# if '' in [username, password, ssh_key_pwd, name, groups, is_active]:
# error = u'带*内容不能为空'
# raise ServerError
# user = User.objects.filter(username=username)
# if user:
# error = u'用户 %s 已存在' % username
# raise ServerError
#
# except ServerError:
# pass
# else:
# try:
# user = db_add_user(username=username,
# password=CRYPTOR.md5_crypt(password),
# name=name, email=email, dept=dept,
# groups=groups, role='CU',
# ssh_key_pwd=CRYPTOR.md5_crypt(ssh_key_pwd),
# ldap_pwd=CRYPTOR.encrypt(ldap_pwd),
# is_active=is_active,
# date_joined=datetime.datetime.now())
#
# server_add_user(username, password, ssh_key_pwd)
# if LDAP_ENABLE:
# ldap_add_user(username, ldap_pwd)
#
# except Exception, e:
# error = u'添加用户 %s 失败 %s ' % (username, e)
# try:
# db_del_user(username)
# server_del_user(username)
# if LDAP_ENABLE:
# ldap_del_user(username)
# except Exception:
# pass
# else:
# mail_title = u'恭喜你的跳板机用户添加成功 Jumpserver'
# mail_msg = """
# Hi, %s
# 您的用户名: %s
# 您的部门: %s
# 您的角色: %s
# 您的web登录密码 %s
# 您的ssh密钥文件密码 %s
# 密钥下载地址: http://%s:%s/juser/down_key/?id=%s
# 说明: 请登陆后再下载密钥!
# """ % (name, username, dept.name, '普通用户',
# password, ssh_key_pwd, SEND_IP, SEND_PORT, user.id)
# send_mail(mail_title, mail_msg, MAIL_FROM, [email], fail_silently=False)
# msg = u'添加用户 %s 成功! 用户密码已发送到 %s 邮箱!' % (username, email)
#
# return render_to_response('juser/user_add.html', locals(), context_instance=RequestContext(request))
@require_role(role='super')
def user_list(request):
user_role = {'SU': u'超级管理员', 'GA': u'组管理员', 'CU': u'普通用户'}
@ -365,31 +230,6 @@ def user_list(request):
return my_render('juser/user_list.html', locals(), request)
# @require_role(role='admin')
# def user_list_adm(request):
# user_role = {'SU': u'超级管理员', 'GA': u'组管理员', 'CU': u'普通用户'}
# header_title, path1, path2 = '查看用户', '用户管理', '用户列表'
# keyword = request.GET.get('keyword', '')
# user, dept = get_session_user_dept(request)
# gid = request.GET.get('gid', '')
# contact_list = dept.user_set.all().order_by('name')
#
# if gid:
# if not validate(request, user_group=[gid]):
# return HttpResponseRedirect('/juser/user_list/')
# user_group = UserGroup.objects.filter(id=gid)
# if user_group:
# user_group = user_group[0]
# contact_list = user_group.user_set.all()
#
# if keyword:
# contact_list = contact_list.filter(Q(username__icontains=keyword) | Q(name__icontains=keyword)).order_by('name')
#
# contact_list, p, contacts, page_range, current_page, show_first, show_end = pages(contact_list, request)
#
# return render_to_response('juser/user_list.html', locals(), context_instance=RequestContext(request))
@require_role(role='user')
def user_detail(request):
header_title, path1, path2 = '用户详情', '用户管理', '用户详情'
@ -420,8 +260,12 @@ def user_del(request):
user_ids = request.GET.get('id', '')
user_id_list = user_ids.split(',')
for user_id in user_id_list:
User.objects.filter(id=user_id).delete()
user = get_object(User, id=user_id)
if user:
assets = user_permed(user)
result = _public_perm_api({'type': 'del_user', 'user': user, 'asset': assets})
print result
user.delete()
return HttpResponse('删除成功')
@ -540,6 +384,7 @@ def user_edit(request):
admin_groups=admin_groups,
role=role_post,
is_active=is_active)
_public_perm_api({'type': 'del_user', 'user': user, 'asset': user_permed(user)})
if email_need:
msg = u"""
@ -561,59 +406,6 @@ def user_edit(request):
# @require_role(role='admin')
def user_edit_adm(request):
pass
# header_title, path1, path2 = '编辑用户', '用户管理', '用户编辑'
# user, dept = get_session_user_dept(request)
# if request.method == 'GET':
# user_id = request.GET.get('id', '')
# if not user_id:
# return HttpResponseRedirect('/juser/user_list/')
#
# if not validate(request, user=[user_id]):
# return HttpResponseRedirect('/juser/user_list/')
#
# user = User.objects.filter(id=user_id)
# dept_all = DEPT.objects.all()
# group_all = dept.usergroup_set.all()
# if user:
# user = user[0]
# groups_str = ' '.join([str(group.id) for group in user.group.all()])
#
# else:
# user_id = request.POST.get('user_id', '')
# password = request.POST.get('password', '')
# name = request.POST.get('name', '')
# email = request.POST.get('email', '')
# groups = request.POST.getlist('groups', [])
# ssh_key_pwd = request.POST.get('ssh_key_pwd', '')
# is_active = True if request.POST.get('is_active', '1') == '1' else False
#
# if not validate(request, user=[user_id], user_group=groups):
# return HttpResponseRedirect('/juser/user_edit/')
# if user_id:
# user = User.objects.filter(id=user_id)
# if user:
# user = user[0]
# else:
# return HttpResponseRedirect('/juser/user_list/')
#
# if password != user.password:
# password = CRYPTOR.md5_crypt(password)
#
# if ssh_key_pwd != user.ssh_key_pwd:
# ssh_key_pwd = CRYPTOR.encrypt(ssh_key_pwd)
#
# db_update_user(user_id=user_id,
# password=password,
# name=name,
# email=email,
# groups=groups,
# is_active=is_active,
# ssh_key_pwd=ssh_key_pwd)
#
# return HttpResponseRedirect('/juser/user_list/')
#
# return render_to_response('juser/user_edit.html', locals(), context_instance=RequestContext(request))
#
def profile(request):