Пример #1
0
    def check_rsa(self):
        """
        检查CMDB 密钥配置,没有则创建新的写入数据库
        :return:
        """
        # 检查路径
        self.check_public_path()
        with DBContext('r') as session:
            # 这张表里面直有一条信息,名字:cmdb, 一对密钥
            exist_rsa = session.query(
                SSHConfigs.id, SSHConfigs.id_rsa_pub,
                SSHConfigs.id_rsa).filter(SSHConfigs.name == 'cmdb').first()
            if not exist_rsa:
                # 检查本地是否存在
                local_id_rsa_exist = os.path.exists('{}/id_rsa'.format(
                    os.path.dirname(PUBLIC_KEY)))
                if not local_id_rsa_exist:
                    check_rsa = self.init_rsa()
                    if not check_rsa:
                        return False
                self.save_of()

            elif exist_rsa:
                PUBLIC_KEY_PATH = os.path.dirname(PUBLIC_KEY)
                id_rsa_pub = exist_rsa[1]
                id_rsa = exist_rsa[2]
                cmd1 = 'echo "{}" > {}/id_rsa.pub'.format(
                    id_rsa_pub, PUBLIC_KEY_PATH)
                cmd2 = 'echo "{}" > {}/id_rsa && chmod 600 {}/id_rsa'.format(
                    id_rsa, PUBLIC_KEY_PATH, PUBLIC_KEY_PATH)
                exec_shell(cmd1)
                exec_shell(cmd2)
                return True
            else:
                return True
Пример #2
0
    def get_connection(self, asset_id):
        """
        获取连接成功后的SSH
        :return:
        """
        connect_info = self.get_connect_info(asset_id)
        if not connect_info:
            # color_print('没有匹配到任何主机', color='red')
            return False
#        connect_info = [('172.16.0.120', 22, 'root')]
        ip = connect_info.get('ip')
        port = connect_info.get('port')
        user = connect_info.get('system_user')
        _private_key_txt = connect_info.get('private_key_txt')
        # 将Key写文件
        file_path = '/tmp/{}_private_key'.format(user)
        cmd = 'echo "{}" > {} && chmod 600 {}'.format(
            _private_key_txt, file_path, file_path)
        ret, stdout = exec_shell(cmd)
        if ret != 0:
            print('[ERROR]: PrivateKey文件写文件失败')
            return False

        private_key = paramiko.RSAKey.from_private_key_file(file_path)
        try:
            ssh = paramiko.Transport(ip, port)
            ssh.connect(username=user, pkey=private_key)

            return ssh

        except Exception as e:
            print(e)
Пример #3
0
 def initRsa(self):
     '''Server端生成秘钥对,并写入配置'''
     cmd = 'ssh-keygen -t rsa -P "" -f %s/id_rsa' % self.rsa_dir
     code, ret = exec_shell(cmd)
     if code == 0:
         return True
     else:
         return False
Пример #4
0
 def init_rsa(self):
     '''Server端生成秘钥对'''
     cmd = 'ssh-keygen -t rsa -P "" -f {}/id_rsa'.format(
         os.path.dirname(PUBLIC_KEY))
     code, ret = exec_shell(cmd)
     if code == 0:
         return True
     else:
         return False
Пример #5
0
    def post(self, *args, **kwargs):
        data = json.loads(self.request.body.decode("utf-8"))
        name = data.get('name', None)  # 名称,也是唯一
        system_user = data.get('system_user', None)  # 系统用户
        platform_users = data.get('platform_users', [])  # 平台用户
        priority = data.get('priority', None)  # 优先级
        sudo_list = data.get('sudo_list', None)  # sudo权限
        bash_shell = data.get('bash_shell', None)  # sudo权限
        remarks = data.get('remarks', None)  # 备注

        if not name or not system_user or not priority or not sudo_list or not bash_shell:
            return self.write(dict(code=-2, msg='关键参数不能为空'))

        if not platform_users:
            return self.write(dict(code=-2, msg='请至少选择一个关联用户'))

        if not is_number(priority):
            return self.write(dict(code=-2, msg='优先级必须是数字'))

        with DBContext('r', None, True) as session:
            exist_id = session.query(SystemUser.id).filter(SystemUser.name == name).first()
            exist_priority = session.query(SystemUser.id).filter(SystemUser.priority == int(priority)).first()

        if exist_id:
            return self.write(dict(code=-2, msg='不要重复记录'))

        if exist_priority:
            return self.write(dict(code=-2, msg='优先级冲突'))

        # 新建一个系统用户用来登陆主机,此用户使用密钥认证登陆主机,密钥是自动生成的,生成后保存到数据库里面
        key_name = shortuuid.uuid()
        init_keygen_cmd = 'ssh-keygen -t rsa -P "" -f /tmp/{}'.format(key_name)
        code, ret = exec_shell(init_keygen_cmd)
        if code == 0:
            # 这个系统用户的公钥和私钥是根据name+system_user生成到/tmp下的
            with open('/tmp/{}'.format(key_name), 'r') as id_rsa, open(
                    '/tmp/{}.pub'.format(key_name), 'r') as id_rsa_pub:
                # 对密钥进行加密再写数据库
                mc = MyCryptV2()  # 实例化
                _private_key = mc.my_encrypt(id_rsa.read())
                _public_key = mc.my_encrypt(id_rsa_pub.read())
                # print('加密后的id_rsa--->',_private_key)
                # print('加密后的id_rsa_pub--->',_public_key)
                # print('解密公钥', mc.my_decrypt(_public_key))
                # 生成密钥对写入数据库
                with DBContext('w', None, True) as session:
                    new_system_user = SystemUser(name=name, system_user=system_user, priority=priority,
                                                 sudo_list=sudo_list,
                                                 bash_shell=bash_shell, id_rsa=_private_key, id_rsa_pub=_public_key,
                                                 platform_users=','.join(platform_users),
                                                 remarks=remarks)
                    session.add(new_system_user)
            return self.write(dict(code=0, msg='添加成功'))
        else:
            return self.write(dict(code=-4, msg=ret))
Пример #6
0
 def check_public_path(self):
     """
     检查是否有这个目录,没有目录就新建
     :return:
     """
     PUBLIC_KEY_PATH = os.path.dirname(PUBLIC_KEY)
     cmd = '[ ! -d {} ] && mkdir {} && chmod 700 {} ; '.format(
         PUBLIC_KEY_PATH, PUBLIC_KEY_PATH, PUBLIC_KEY_PATH)
     code, ret = exec_shell(cmd)
     if code == 0:
         return True
     else:
         return False