diff --git a/jperm/perm_api.py b/jperm/perm_api.py index 080f1cb39..ca8645854 100644 --- a/jperm/perm_api.py +++ b/jperm/perm_api.py @@ -161,23 +161,42 @@ def gen_resource(ob, perm=None): user = ob.get('user') if not perm: perm = get_group_user_perm(user) - roles = perm.get('role', {}).keys() - if role not in roles: - return {} - role_assets_all = perm.get('role').get(role).get('asset') - assets = set(role_assets_all) & set(asset_r) - - for asset in assets: - asset_info = get_asset_info(asset) - info = {'hostname': asset.hostname, - 'ip': asset.ip, - 'port': asset_info.get('port', 22), - 'username': role.name, - 'password': CRYPTOR.decrypt(role.password), - 'ssh_key': get_role_key(user, role) - } - res.append(info) + if role: + roles = perm.get('role', {}).keys() # 获取用户所有授权角色 + if role not in roles: + return {} + + role_assets_all = perm.get('role').get(role).get('asset') # 获取用户该角色所有授权主机 + assets = set(role_assets_all) & set(asset_r) # 获取用户提交中合法的主机 + + for asset in assets: + asset_info = get_asset_info(asset) + info = {'hostname': asset.hostname, + 'ip': asset.ip, + 'port': asset_info.get('port', 22), + 'username': role.name, + 'password': CRYPTOR.decrypt(role.password), + 'ssh_key': get_role_key(user, role) + } + res.append(info) + else: + for asset, asset_info in perm.get('asset').items(): + if asset not in asset_r: + continue + asset_info = get_asset_info(asset) + try: + role = sorted(list(perm.get('asset').get(asset).get('role')))[0] + except IndexError: + continue + info = {'hostname': asset.hostname, + 'ip': asset.ip, + 'port': asset_info.get('port', 22), + 'username': role.name, + 'password': CRYPTOR.decrypt(role.password), + 'ssh_key': get_role_key(user, role) + } + res.append(info) elif isinstance(ob, User): if not perm: diff --git a/jumpserver/views.py b/jumpserver/views.py index 4563a9fd4..be47d85d8 100644 --- a/jumpserver/views.py +++ b/jumpserver/views.py @@ -16,7 +16,10 @@ from jumpserver.models import Setting from django.contrib.auth import authenticate, login, logout from django.contrib.auth.decorators import login_required from jlog.models import Log -from jperm.perm_api import get_group_user_perm +from jperm.perm_api import get_group_user_perm, gen_resource +from jasset.models import Asset, IDC +from jperm.ansible_api import MyRunner + def getDaysByNum(num): """ @@ -72,7 +75,7 @@ def get_count_by_date(date_li, item): return len(set(data_count_tmp)) -from jasset.models import Asset, IDC + @require_role(role='user') def index_cu(request): # user_id = request.user.id @@ -181,34 +184,6 @@ def skin_config(request): return render_to_response('skin_config.html') -# def pages(posts, r): -# """分页公用函数""" -# contact_list = posts -# p = paginator = Paginator(contact_list, 10) -# try: -# current_page = int(r.GET.get('page', '1')) -# except ValueError: -# current_page = 1 -# -# page_range = page_list_return(len(p.page_range), current_page) -# -# try: -# contacts = paginator.page(current_page) -# except (EmptyPage, InvalidPage): -# contacts = paginator.page(paginator.num_pages) -# -# if current_page >= 5: -# show_first = 1 -# else: -# show_first = 0 -# if current_page <= (len(p.page_range) - 3): -# show_end = 1 -# else: -# show_end = 0 -# -# return contact_list, p, contacts, page_range, current_page, show_first, show_end - - def is_latest(): node = uuid.getnode() jsn = uuid.UUID(int=node).hex[-12:] @@ -308,166 +283,53 @@ def setting(request): return my_render('setting.html', locals(), request) -def test2(request): - return my_render('test2.html', locals(), request) -# -# def filter_ajax_api(request): -# attr = request.GET.get('attr', 'user') -# value = request.GET.get('value', '') -# if attr == 'user': -# contact_list = User.objects.filter(name__icontains=value) -# elif attr == "user_group": -# contact_list = UserGroup.objects.filter(name__icontains=value) -# elif attr == "asset": -# contact_list = Asset.objects.filter(ip__icontains=value) -# elif attr == "asset": -# contact_list = BisGroup.objects.filter(name__icontains=value) -# -# return render_to_response('filter_ajax_api.html', locals()) -# -# -# def install(request): -# from juser.models import DEPT, User -# if User.objects.filter(id=5000): -# return http_error(request, 'Jumpserver已初始化,不能重复安装!') -# -# dept = DEPT(id=1, name="超管部", comment="超级管理部门") -# dept.save() -# dept2 = DEPT(id=2, name="默认", comment="默认部门") -# dept2.save() -# IDC(id=1, name="默认", comment="默认IDC").save() -# BisGroup(id=1, name="ALL", dept=dept, comment="所有主机组").save() -# -# User(id=5000, username="admin", password=PyCrypt.md5_crypt('admin'), -# name='admin', email='admin@jumpserver.org', role='SU', is_active=True, dept=dept).save() -# return http_success(request, u'Jumpserver初始化成功') -# -# -# def download(request): -# return render_to_response('download.html', locals(), context_instance=RequestContext(request)) -# -# -# def transfer(sftp, filenames): -# # pool = Pool(processes=5) -# for filename, file_path in filenames.items(): -# print filename, file_path -# sftp.put(file_path, '/tmp/%s' % filename) -# # pool.apply_async(transfer, (sftp, file_path, '/tmp/%s' % filename)) -# sftp.close() -# # pool.close() -# # pool.join() -# -# -# def upload(request): -# pass -# # user, dept = get_session_user_dept(request) -# # if request.method == 'POST': -# # hosts = request.POST.get('hosts') -# # upload_files = request.FILES.getlist('file[]', None) -# # upload_dir = "/tmp/%s" % user.username -# # is_dir(upload_dir) -# # date_now = datetime.datetime.now().strftime("%Y%m%d%H%M%S") -# # hosts_list = hosts.split(',') -# # user_hosts = [asset.ip for asset in user.get_asset()] -# # unperm_hosts = [] -# # filenames = {} -# # for ip in hosts_list: -# # if ip not in user_hosts: -# # unperm_hosts.append(ip) -# # -# # if not hosts: -# # return HttpResponseNotFound(u'地址不能为空') -# # -# # if unperm_hosts: -# # print hosts_list -# # return HttpResponseNotFound(u'%s 没有权限.' % ', '.join(unperm_hosts)) -# # -# # for upload_file in upload_files: -# # file_path = '%s/%s.%s' % (upload_dir, upload_file.name, date_now) -# # filenames[upload_file.name] = file_path -# # f = open(file_path, 'w') -# # for chunk in upload_file.chunks(): -# # f.write(chunk) -# # f.close() -# # -# # sftps = [] -# # for host in hosts_list: -# # username, password, host, port = get_connect_item(user.username, host) -# # try: -# # t = paramiko.Transport((host, port)) -# # t.connect(username=username, password=password) -# # sftp = paramiko.SFTPClient.from_transport(t) -# # sftps.append(sftp) -# # except paramiko.AuthenticationException: -# # return HttpResponseNotFound(u'%s 连接失败.' % host) -# # -# # # pool = Pool(processes=5) -# # for sftp in sftps: -# # transfer(sftp, filenames) -# # # pool.close() -# # # pool.join() -# # return HttpResponse('传送成功') -# # -# # return render_to_response('upload.html', locals(), context_instance=RequestContext(request)) -# -# -# def node_auth(request): -# username = request.POST.get('username', ' ') -# seed = request.POST.get('seed', ' ') -# filename = request.POST.get('filename', ' ') -# user = User.objects.filter(username=username, password=seed) -# auth = 1 -# if not user: -# auth = 0 -# if not filename.startswith('/opt/jumpserver/logs/connect/'): -# auth = 0 -# if auth: -# result = {'auth': {'username': username, 'result': 'success'}} -# else: -# result = {'auth': {'username': username, 'result': 'failed'}} -# -# return HttpResponse(json.dumps(result, sort_keys=True, indent=2), content_type='application/json') - - -####################### liuzheng's test(start) ######################## -from django.contrib.auth.decorators import login_required -from juser.models import Document - @login_required(login_url='/login') def upload(request): - if request.method == 'GET': - machines = [{'name':'aaa'}] - return render_to_response('upload.html', locals(), context_instance=RequestContext(request)) - elif request.method == 'POST': + user = request.user + assets = get_group_user_perm(user).get('asset').keys() + + asset_select = [] + if request.method == 'POST': + asset_ids = request.POST.getlist('asset_ids', '') upload_files = request.FILES.getlist('file[]', None) - for file in upload_files: - print file - newdoc = Document(docfile=file, user_id=request.user.id) - newdoc.save() - return HttpResponse("success") - else: - return HttpResponse("ERROR") + date_now = datetime.datetime.now().strftime("%Y%m%d%H%M%S") + upload_dir = "/tmp/%s/%s" % (user.username, date_now) + mkdir(upload_dir) + filenames = {} + for asset_id in asset_ids: + asset_select.append(get_object(Asset, id=asset_id)) + + if not set(asset_select).issubset(set(assets)): + illegal_asset = set(asset_select).issubset(set(assets)) + return HttpResponse('没有权限的服务器 %s' % ','.join([asset.hostname for asset in illegal_asset])) + + for upload_file in upload_files: + file_path = '%s/%s' % (upload_dir, upload_file.name) + filenames[upload_file.name] = file_path + with open(file_path, 'w') as f: + for chunk in upload_file.chunks(): + f.write(chunk) + + res = gen_resource({'user': user, 'asset': asset_select}) + runner = MyRunner(res) + ret = runner.run('copy', module_args='src=%s dest=%s directory_mode' % (upload_dir, '/tmp/hello/'), pattern='*') + logger.debug(ret) + error = '上传失败: ' + if ret.get('dark'): + error += ','.join(ret.get('dark').keys()) + + for asset, info in ret.get('contacted').items(): + if info.get('msg'): + error += ',%s' % asset + if error: + return HttpResponse(error, status=500) + return HttpResponse('传送成功') + return my_render('upload.html', locals(), request) + @login_required(login_url='/login') def download(request): documents = [] - for doc in Document.objects.filter(user_id=request.user.id).all(): - documents.append('/'.join(str(doc.docfile).split('/')[2:])) return render_to_response('download.html', locals(), context_instance=RequestContext(request)) -def download_file(request, path): - # TODO: get downlode file and make sure it is exist! - # by liuzheng - filepath = 'upload/' + str(request.user.id)+'/'+path - return HttpResponse(filepath) - -def node_auth(request): - return HttpResponse('nothing') -def httperror(request): - return HttpResponse('nothing') -def base(request): - return HttpResponse('nothing') -def install(request): - return HttpResponse('nothing') - -####################### liuzheng's test(end) ######################## \ No newline at end of file + diff --git a/juser/views.py b/juser/views.py index f204a53c5..4f1183d84 100644 --- a/juser/views.py +++ b/juser/views.py @@ -9,6 +9,7 @@ from django.contrib.auth.decorators import login_required from django.db.models import Q from juser.user_api import * +from jperm.perm_api import get_group_user_perm MAIL_FROM = EMAIL_HOST_USER @@ -486,9 +487,9 @@ def down_key(request): response = HttpResponse(data, content_type='application/octet-stream') response['Content-Disposition'] = 'attachment; filename=%s' % os.path.basename(private_key_file) return response - return HttpResponse('No Key File. Contact Admin.') -from jperm.perm_api import get_group_user_perm + + @require_role(role='user') def RunCommand(request): if request.method == 'GET': diff --git a/templates/upload.html b/templates/upload.html index fb50a7cfa..506c22ac5 100644 --- a/templates/upload.html +++ b/templates/upload.html @@ -1,5 +1,10 @@ {% extends 'base.html' %} {% load mytags %} +{% block self_head_css_js %} + + + +{% endblock %} {% block content %} {% include 'nav_cat_bar.html' %}