def perm_role_edit(request): """ edit role page """ # 渲染数据 header_title, path1, path2 = "系统用户", "系统用户管理", "系统用户编辑" # 渲染数据 role_id = request.GET.get("id") role = PermRole.objects.get(id=role_id) role_pass = CRYPTOR.decrypt(role.password) sudo_all = PermSudo.objects.all() role_sudos = role.sudo.all() sudo_all = PermSudo.objects.all() if request.method == "GET": return my_render('jperm/perm_role_edit.html', locals(), request) if request.method == "POST": # 获取 POST 数据 role_name = request.POST.get("role_name") role_password = request.POST.get("role_password") role_comment = request.POST.get("role_comment") role_sudo_names = request.POST.getlist("sudo_name") role_sudos = [ PermSudo.objects.get(id=sudo_id) for sudo_id in role_sudo_names ] key_content = request.POST.get("role_key", "") if len(role_password) > 64: raise ServerError('密码长度不能超过64位!') try: if not role: raise ServerError('该系统用户不能存在') if role_name == "root": raise ServerError('禁止使用root用户作为系统用户,这样非常危险!') if role_password: encrypt_pass = CRYPTOR.encrypt(role_password) role.password = encrypt_pass # 生成随机密码,生成秘钥对 if key_content: try: key_path = gen_keys(key=key_content, key_path_dir=role.key_path) except SSHException: raise ServerError('输入的密钥不合法') logger.debug('Recreate role key: %s' % role.key_path) # 写入数据库 role.name = role_name role.comment = role_comment role.sudo = role_sudos role.save() msg = "更新系统用户: %s" % role.name return HttpResponseRedirect(reverse('role_list')) except ServerError as e: error = e return my_render('jperm/perm_role_edit.html', locals(), request)
def perm_role_add(request): """ add role page """ # 渲染数据 header_title, path1, path2 = "系统用户", "系统用户管理", "添加系统用户" login_user_id = request.user.id if not login_user_id: return HttpResponseRedirect(reverse('index')) login_user = User.objects.get(id=login_user_id) productlines = ProductLine.objects.all() sudos = PermSudo.objects.all().filter(productLine=login_user.productLine) if request.method == "POST": # 获取参数: name, comment name = request.POST.get("role_name", "").strip() comment = request.POST.get("role_comment", "") password = request.POST.get("role_password", "") key_content = request.POST.get("role_key", "") sudo_ids = request.POST.getlist('sudo_name') productline_name = request.POST.get('productline_name', '') productLine = get_object_or_404(ProductLine, name=productline_name) try: if get_object(PermRole, name=name, productLine=productLine): raise ServerError(u'已经存在该用户 %s' % name) if name == "root": raise ServerError(u'禁止使用root用户作为系统用户,这样非常危险!') default = get_object(Setting, name='default') if len(password) > 64: raise ServerError(u'密码长度不能超过64位!') if password: encrypt_pass = CRYPTOR.encrypt(password) else: encrypt_pass = CRYPTOR.encrypt(CRYPTOR.gen_rand_pass(20)) # 生成随机密码,生成秘钥对 sudos_obj = [ get_object(PermSudo, id=sudo_id) for sudo_id in sudo_ids ] if key_content: try: key_path = gen_keys(key=key_content) except SSHException, e: raise ServerError(e) else: key_path = gen_keys() logger.debug('generate role key: %s' % key_path) role = PermRole(name=name, productLine=productLine, comment=comment, password=encrypt_pass, key_path=key_path) role.save() role.sudo = sudos_obj msg = u"添加系统用户: %s" % name return HttpResponseRedirect(reverse('role_list'))
def perm_role_edit(request): """ edit role page """ # 渲染数据 header_title, path1, path2 = "系统用户", "系统用户管理", "系统用户编辑" # 渲染数据 role_id = request.GET.get("id") role = PermRole.objects.get(id=role_id) role_pass = CRYPTOR.decrypt(role.password) sudo_all = PermSudo.objects.all() role_sudos = role.sudo.all() sudo_all = PermSudo.objects.all() if request.method == "GET": return my_render('jperm/perm_role_edit.html', locals(), request) if request.method == "POST": # 获取 POST 数据 role_name = request.POST.get("role_name") role_password = request.POST.get("role_password") role_comment = request.POST.get("role_comment") role_sudo_names = request.POST.getlist("sudo_name") role_sudos = [PermSudo.objects.get(id=sudo_id) for sudo_id in role_sudo_names] key_content = request.POST.get("role_key", "") if len(role_password) > 64: raise ServerError(u'密码长度不能超过64位!') try: if not role: raise ServerError('该系统用户不能存在') if role_name == "root": raise ServerError(u'禁止使用root用户作为系统用户,这样非常危险!') if role_password: encrypt_pass = CRYPTOR.encrypt(role_password) role.password = encrypt_pass # 生成随机密码,生成秘钥对 if key_content: try: key_path = gen_keys(key=key_content, key_path_dir=role.key_path) except SSHException: raise ServerError('输入的密钥不合法') logger.debug('Recreate role key: %s' % role.key_path) # 写入数据库 role.name = role_name role.comment = role_comment role.sudo = role_sudos role.save() msg = u"更新系统用户: %s" % role.name return HttpResponseRedirect(reverse('role_list')) except ServerError, e: error = e
def setting(request): header_title, path1 = '项目设置', '设置' setting_default = get_object(Setting, name='default') if request.method == "POST": try: setting_raw = request.POST.get('setting', '') if setting_raw == 'default': username = request.POST.get('username', '') port = request.POST.get('port', '') password = request.POST.get('password', '') private_key = request.POST.get('key', '') if len(password) > 30: raise ServerError('秘密长度不能超过30位!') if '' in [username, port]: return ServerError('所填内容不能为空, 且密码和私钥填一个') else: private_key_dir = os.path.join(settings.BASE_DIR, 'keys', 'default') private_key_path = os.path.join(private_key_dir, 'admin_user.pem') mkdir(private_key_dir) if private_key: with open(private_key_path, 'w') as f: f.write(private_key) os.chmod(private_key_path, 0o600) if setting_default: if password: password_encode = CRYPTOR.encrypt(password) else: password_encode = password Setting.objects.filter(name='default').update( field1=username, field2=port, field3=password_encode, field4=private_key_path) else: password_encode = CRYPTOR.encrypt(password) setting_r = Setting(name='default', field1=username, field2=port, field3=password_encode, field4=private_key_path).save() msg = "设置成功" except ServerError as e: error = e.message return render(request, 'setting.html', locals())
def perm_role_add(request): """ add role page """ # 渲染数据 header_title, path1, path2 = "系统用户", "系统用户管理", "添加系统用户" sudos = PermSudo.objects.all() if request.method == "POST": # 获取参数: name, comment name = request.POST.get("role_name", "").strip() comment = request.POST.get("role_comment", "") password = request.POST.get("role_password", "") key_content = request.POST.get("role_key", "") sudo_ids = request.POST.getlist('sudo_name') try: if get_object(PermRole, name=name): raise ServerError('已经存在该用户 %s' % name) if name == "root": raise ServerError('禁止使用root用户作为系统用户,这样非常危险!') default = get_object(Setting, name='default') if len(password) > 64: raise ServerError('密码长度不能超过64位!') if password: encrypt_pass = CRYPTOR.encrypt(password) else: encrypt_pass = CRYPTOR.encrypt(CRYPTOR.gen_rand_pass(20)) # 生成随机密码,生成秘钥对 sudos_obj = [ get_object(PermSudo, id=sudo_id) for sudo_id in sudo_ids ] if key_content: try: key_path = gen_keys(key=key_content) except SSHException as e: raise ServerError(e) else: key_path = gen_keys() logger.debug('generate role key: %s' % key_path) role = PermRole(name=name, comment=comment, password=encrypt_pass, key_path=key_path) role.save() role.sudo = sudos_obj msg = "添加系统用户: %s" % name return HttpResponseRedirect(reverse('role_list')) except ServerError as e: error = e return my_render('jperm/perm_role_add.html', locals(), request)
def perm_role_add(request): """ add role page """ # 渲染数据 header_title, path1, path2 = "系统用户", "系统用户管理", "添加系统用户" sudos = PermSudo.objects.all() if request.method == "POST": # 获取参数: name, comment name = request.POST.get("role_name", "").strip() comment = request.POST.get("role_comment", "") password = request.POST.get("role_password", "") key_content = request.POST.get("role_key", "") sudo_ids = request.POST.getlist('sudo_name') try: if get_object(PermRole, name=name): raise ServerError(u'已经存在该用户 %s' % name) if name == "root": raise ServerError(u'禁止使用root用户作为系统用户,这样非常危险!') default = get_object(Setting, name='default') if len(password) > 64: raise ServerError(u'密码长度不能超过64位!') if password: encrypt_pass = CRYPTOR.encrypt(password) else: encrypt_pass = CRYPTOR.encrypt(CRYPTOR.gen_rand_pass(20)) # 生成随机密码,生成秘钥对 sudos_obj = [get_object(PermSudo, id=sudo_id) for sudo_id in sudo_ids] if key_content: try: key_path = gen_keys(key=key_content) except SSHException, e: raise ServerError(e) else: key_path = gen_keys() logger.debug('generate role key: %s' % key_path) role = PermRole(name=name, comment=comment, password=encrypt_pass, key_path=key_path) role.save() role.sudo = sudos_obj msg = u"添加系统用户: %s" % name return HttpResponseRedirect(reverse('role_list'))
def get_connect_info(self): """ 获取需要登陆的主机的信息和映射用户的账号密码 """ asset_info = get_asset_info(self.asset) role_key = get_role_key(self.user, self.role) # 获取角色的key,因为ansible需要权限是600,所以统一生成用户_角色key role_pass = CRYPTOR.decrypt(self.role.password) connect_info = {'user': self.user, 'asset': self.asset, 'ip': asset_info.get('ip'), 'port': int(asset_info.get('port')), 'role_name': self.role.name, 'role_pass': role_pass, 'role_key': role_key} return connect_info
def get_connect_info(self): """ 获取需要登陆的主机的信息和映射用户的账号密码 """ asset_info = get_asset_info(self.asset) role_key = get_role_key(self.user, self.role) # 获取角色的key,因为ansible需要权限是600,所以统一生成用户_角色key role_pass = CRYPTOR.decrypt(self.role.password) connect_info = {'user': self.user, 'asset': self.asset, 'ip': asset_info.get('ip'), 'port': int(asset_info.get('port')), 'role_name': self.role.name, 'role_pass': role_pass, 'role_key': role_key} logger.debug(connect_info) return connect_info
def root_all_check(): print '开始检查资产root账户可用性' assets = Asset.objects.filter(~Q(group__name__contains='it')) asset_result = {} asset_result['success'] = [] asset_result['failed'] = [] for asset in assets: username = asset.username password = CRYPTOR.decrypt(asset.password) port = asset.port result = ssh_connect_check(asset.ip, username, password, port) if result: asset_result['success'].append(asset.hostname) else: asset_result['failed'].append(asset.hostname) return asset_result
def get_connect_info(self): """ 获取需要登陆的主机的信息和映射用户的账号密码 """ asset_info = get_asset_info(self.asset, self.user) role_key = get_role_key(self.user, self.role) role_pass = CRYPTOR.decrypt('') connect_info = { 'user': self.user, 'asset': self.asset, 'ip': asset_info.get('ip'), 'port': int(asset_info.get('port')), 'role_name': self.role, 'role_pass': role_pass, 'role_key': role_key } return connect_info
def get_connect_info(self): """ 获取需要登陆的主机的信息和映射用户的账号密码 """ asset_info = get_asset_info(self.asset) role_key = get_role_key(self.user, self.role) # 获取角色的key,因为ansible需要权限是600,所以统一生成用户_角色key role_pass = CRYPTOR.decrypt(self.role.password) connect_info = { "user": self.user, "asset": self.asset, "ip": asset_info.get("ip"), "port": int(asset_info.get("port")), "role_name": self.role.name, "role_pass": role_pass, "role_key": role_key, } logger.debug(connect_info) return connect_info
def asset_add(request): """ Asset add view 添加资产 """ header_title, path1, path2 = '添加资产', '资产管理', '添加资产' asset_group_all = AssetGroup.objects.all() af = AssetForm() default_setting = get_object(Setting, name='default') default_port = default_setting.field2 if default_setting else '' if request.method == 'POST': af_post = AssetForm(request.POST) ip = request.POST.get('ip', '') hostname = request.POST.get('hostname', '') is_active = True if request.POST.get('is_active') == '1' else False use_default_auth = request.POST.get('use_default_auth', '') try: if Asset.objects.filter(hostname=str(hostname)): error = '该主机名 %s 已存在!' % hostname raise ServerError(error) if len(hostname) > 54: error = "主机名长度不能超过53位!" raise ServerError(error) except ServerError: pass else: if af_post.is_valid(): asset_save = af_post.save(commit=False) if not use_default_auth: password = request.POST.get('password', '') password_encode = CRYPTOR.encrypt(password) asset_save.password = password_encode if not ip: asset_save.ip = hostname asset_save.is_active = True if is_active else False asset_save.save() af_post.save_m2m() msg = '主机 %s 添加成功' % hostname else: esg = '主机 %s 添加失败' % hostname return my_render('jasset/asset_add.html', locals(), request)
def excel_to_db(excel_file): """ Asset add batch function """ try: data = xlrd.open_workbook(filename=None, file_contents=excel_file.read()) except Exception: return False else: table = data.sheets()[0] rows = table.nrows for row_num in range(1, rows): row = table.row_values(row_num) if row: group_instance = [] ip, port, hostname, use_default_auth, username, password, group = row if get_object(Asset, hostname=hostname): continue if isinstance(password, int) or isinstance(password, float): password = str(int(password)) use_default_auth = 1 if use_default_auth == '默认' else 0 password_encode = CRYPTOR.encrypt(password) if password else '' if hostname: asset = Asset(ip=ip, port=port, hostname=hostname, use_default_auth=use_default_auth, username=username, password=password_encode) asset.save() group_list = group.split('/') for group_name in group_list: group = get_object(AssetGroup, name=group_name) if group: group_instance.append(group) if group_instance: asset.group = group_instance asset.save() return True
def get_rand_pass(): """ get a reandom password. """ CRYPTOR.gen_rand_pass(20)
def asset_edit_batch(request): af = AssetForm() name = request.user.username asset_group_all = AssetGroup.objects.all() if request.method == 'POST': env = request.POST.get('env', '') idc_id = request.POST.get('idc', '') port = request.POST.get('port', '') use_default_auth = request.POST.get('use_default_auth', '') username = request.POST.get('username', '') password = request.POST.get('password', '') group = request.POST.getlist('group', []) cabinet = request.POST.get('cabinet', '') comment = request.POST.get('comment', '') asset_id_all = str(request.GET.get('asset_id_all', '')) asset_id_all = asset_id_all.split(',') for asset_id in asset_id_all: alert_list = [] asset = get_object(Asset, id=asset_id) if asset: if env: if asset.env != env: asset.env = env alert_list.append(['运行环境', asset.env, env]) if idc_id: idc = get_object(IDC, id=idc_id) name_old = asset.idc.name if asset.idc else '' if idc and idc.name != name_old: asset.idc = idc alert_list.append(['机房', name_old, idc.name]) if port: if str(asset.port) != port: asset.port = port alert_list.append(['端口号', asset.port, port]) if use_default_auth: if use_default_auth == 'default': asset.use_default_auth = 1 asset.username = '' asset.password = '' alert_list.append( ['使用默认管理账号', asset.use_default_auth, '默认']) elif use_default_auth == 'user_passwd': asset.use_default_auth = 0 asset.username = username password_encode = CRYPTOR.encrypt(password) asset.password = password_encode alert_list.append( ['使用默认管理账号', asset.use_default_auth, username]) if group: group_new, group_old, group_new_name, group_old_name = [], asset.group.all( ), [], [] for group_id in group: g = get_object(AssetGroup, id=group_id) if g: group_new.append(g) if not set(group_new) < set(group_old): group_instance = list(set(group_new) | set(group_old)) for g in group_instance: group_new_name.append(g.name) for g in group_old: group_old_name.append(g.name) asset.group = group_instance alert_list.append([ '主机组', ','.join(group_old_name), ','.join(group_new_name) ]) if cabinet: if asset.cabinet != cabinet: asset.cabinet = cabinet alert_list.append(['机柜号', asset.cabinet, cabinet]) if comment: if asset.comment != comment: asset.comment = comment alert_list.append(['备注', asset.comment, comment]) asset.save() if alert_list: recode_name = str(name) + ' - ' + '批量' AssetRecord.objects.create(asset=asset, username=recode_name, content=alert_list) return my_render('jasset/asset_update_status.html', locals(), request) return my_render('jasset/asset_edit_batch.html', locals(), request)
def asset_edit(request): """ edit a asset 修改主机 """ header_title, path1, path2 = '修改资产', '资产管理', '修改资产' asset_id = request.GET.get('id', '') username = request.user.username asset = get_object(Asset, id=asset_id) if asset: password_old = asset.password # asset_old = copy_model_instance(asset) af = AssetForm(instance=asset) if request.method == 'POST': af_post = AssetForm(request.POST, instance=asset) ip = request.POST.get('ip', '') hostname = request.POST.get('hostname', '') password = request.POST.get('password', '') is_active = True if request.POST.get('is_active') == '1' else False use_default_auth = request.POST.get('use_default_auth', '') try: asset_test = get_object(Asset, hostname=hostname) if asset_test and asset_id != str(asset_test.id): emg = '该主机名 %s 已存在!' % hostname raise ServerError(emg) if len(hostname) > 54: emg = '主机名长度不能超过54位!' raise ServerError(emg) else: if af_post.is_valid(): af_save = af_post.save(commit=False) if use_default_auth: af_save.username = '' af_save.password = '' # af_save.port = None else: if password: password_encode = CRYPTOR.encrypt(password) af_save.password = password_encode else: af_save.password = password_old af_save.is_active = True if is_active else False af_save.save() af_post.save_m2m() # asset_new = get_object(Asset, id=asset_id) # asset_diff_one(asset_old, asset_new) info = asset_diff(af_post.__dict__.get('initial'), request.POST) db_asset_alert(asset, username, info) smg = '主机 %s 修改成功' % ip else: emg = '主机 %s 修改失败' % ip raise ServerError(emg) except ServerError as e: error = e.message return my_render('jasset/asset_edit.html', locals(), request) return HttpResponseRedirect( reverse('asset_detail') + '?id=%s' % asset_id) return my_render('jasset/asset_edit.html', locals(), request)
def perm_role_push(request): """ the role push page """ # 渲染数据 header_title, path1, path2 = "系统用户", "系统用户管理", "系统用户推送" role_id = request.GET.get('id') asset_ids = request.GET.get('asset_id') role = get_object(PermRole, id=role_id) assets = Asset.objects.all() asset_groups = AssetGroup.objects.all() if asset_ids: need_push_asset = [get_object(Asset, id=asset_id) for asset_id in asset_ids.split(',')] if request.method == "POST": # 获取推荐角色的名称列表 # 计算出需要推送的资产列表 asset_ids = request.POST.getlist("assets") asset_group_ids = request.POST.getlist("asset_groups") assets_obj = [Asset.objects.get(id=asset_id) for asset_id in asset_ids] asset_groups_obj = [AssetGroup.objects.get(id=asset_group_id) for asset_group_id in asset_group_ids] group_assets_obj = [] for asset_group in asset_groups_obj: group_assets_obj.extend(asset_group.asset_set.all()) calc_assets = list(set(assets_obj) | set(group_assets_obj)) push_resource = gen_resource(calc_assets) # 调用Ansible API 进行推送 password_push = True if request.POST.get("use_password") else False key_push = True if request.POST.get("use_publicKey") else False task = MyTask(push_resource) ret = {} # 因为要先建立用户,所以password 是必选项,而push key是在 password也完成的情况下的 可选项 # 1. 以秘钥 方式推送角色 if key_push: ret["pass_push"] = task.add_user(role.name, CRYPTOR.decrypt(role.password)) ret["key_push"] = task.push_key(role.name, os.path.join(role.key_path, 'id_rsa.pub')) # 2. 推送账号密码 elif password_push: ret["pass_push"] = task.add_user(role.name, CRYPTOR.decrypt(role.password)) # 3. 推送sudo配置文件 if password_push or key_push: sudo_list = set([sudo for sudo in role.sudo.all()]) # set(sudo1, sudo2, sudo3) if sudo_list: ret['sudo'] = task.push_sudo_file([role], sudo_list) logger.debug('推送role结果: %s' % ret) success_asset = {} failed_asset = {} logger.debug(ret) for push_type, result in ret.items(): if result.get('failed'): for hostname, info in result.get('failed').items(): if hostname in failed_asset.keys(): if info in failed_asset.get(hostname): failed_asset[hostname] += info else: failed_asset[hostname] = info for push_type, result in ret.items(): if result.get('ok'): for hostname, info in result.get('ok').items(): if hostname in failed_asset.keys(): continue elif hostname in success_asset.keys(): if str(info) in success_asset.get(hostname, ''): success_asset[hostname] += str(info) else: success_asset[hostname] = str(info) # 推送成功 回写push表 for asset in calc_assets: push_check = PermPush.objects.filter(role=role, asset=asset) if push_check: func = push_check.update else: def func(**kwargs): PermPush(**kwargs).save() if failed_asset.get(asset.hostname): func(is_password=password_push, is_public_key=key_push, role=role, asset=asset, success=False, result=failed_asset.get(asset.hostname)) else: func(is_password=password_push, is_public_key=key_push, role=role, asset=asset, success=True) if not failed_asset: msg = u'系统用户 %s 推送成功[ %s ]' % (role.name, ','.join(success_asset.keys())) else: error = u'系统用户 %s 推送失败 [ %s ], 推送成功 [ %s ] 进入系统用户详情,查看失败原因' % (role.name, ','.join(failed_asset.keys()), ','.join(success_asset.keys())) return my_render('jperm/perm_role_push.html', locals(), request)