角色key问题修复

pull/26/head
ibuler 2015-11-25 16:01:07 +08:00
parent 6fe6342ca4
commit f760df1e34
3 changed files with 30 additions and 17 deletions

View File

@ -2,7 +2,8 @@
import random
import os.path
import shutil
from paramiko import SSHException
from paramiko.rsakey import RSAKey
from jumpserver.api import mkdir
from uuid import uuid4
@ -28,21 +29,32 @@ def updates_dict(*args):
return result
def gen_keys(gen=True):
def gen_keys(key="", key_path_dir=""):
"""
在KEY_DIR下创建一个 uuid命名的目录
并且在该目录下 生产一对秘钥
:return: 返回目录名(uuid)
"""
key_basename = "key-" + uuid4().hex
key_path_dir = os.path.join(KEY_DIR, 'role_key', key_basename)
mkdir(key_path_dir, mode=0755)
if not gen:
return key_path_dir
key = RSAKey.generate(2048)
if not key_path_dir:
key_path_dir = os.path.join(KEY_DIR, 'role_key', key_basename)
private_key = os.path.join(key_path_dir, 'id_rsa')
public_key = os.path.join(key_path_dir, 'id_rsa.pub')
key.write_private_key_file(private_key)
mkdir(key_path_dir, mode=0755)
if not key:
key = RSAKey.generate(2048)
key.write_private_key_file(private_key)
else:
key_file = os.path.join(key_path_dir, 'id_rsa')
with open(key_file, 'w') as f:
f.write(key)
f.close()
with open(key_file) as f:
try:
key = RSAKey.from_private_key(f)
except SSHException:
shutil.rmtree(key_path_dir, ignore_errors=True)
raise SSHException
os.chmod(private_key, 0644)
with open(public_key, 'w') as content_file:

View File

@ -1,6 +1,7 @@
# -*- coding: utf-8 -*-
from django.db.models import Q
from paramiko import SSHException
from jperm.perm_api import *
from juser.user_api import gen_ssh_key
@ -273,20 +274,19 @@ def perm_role_add(request):
encrypt_pass = CRYPTOR.encrypt(CRYPTOR.gen_rand_pass(20))
# 生成随机密码,生成秘钥对
if key_content:
key_path = gen_keys(gen=False)
with open(os.path.join(key_path, 'id_rsa'), 'w') as f:
f.write(key_content)
try:
key_path = gen_keys(key=key_content)
except SSHException:
raise ServerError('输入的密钥不合法')
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()
msg = u"添加角色: %s" % name
return HttpResponseRedirect('/perm/role/')
return HttpResponseRedirect('/jperm/role/')
except ServerError, e:
error = e
else:
return HttpResponse(u"不支持该操作")
return my_render('jperm/perm_role_add.html', locals(), request)
@ -368,8 +368,10 @@ def perm_role_edit(request):
role.password = encrypt_pass
# 生成随机密码,生成秘钥对
if key_content:
with open(os.path.join(role.key_path, 'id_rsa'), 'w') as f:
f.write(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

View File

@ -47,7 +47,6 @@
<span class="help-block m-b-none">如果不添加密码,会自动生成</span>
</div>
</div>
<div class="hr-line-dashed"></div>
<div class="form-group">
<label for="role_key" class="col-sm-2 control-label">角色密钥</label>
<div class="col-sm-8">