예제 #1
0
def create_users(argvs):
    '''
    create little_finger access user
    :param argvs:
    :return:
    '''
    if '-f' in argvs:
        user_file  = argvs[argvs.index("-f") +1 ]
    else:
        print_err("invalid usage, should be:\ncreateusers -f <the new users file>",quit=True)

    source = yaml_parser(user_file)
    if source:
        for key,val in source.items():
            print(key,val)
            obj = models.UserProfile(username=key,password=val.get('password'))
            if val.get('groups'):
                groups = session.query(models.Group).filter(models.Group.name.in_(val.get('groups'))).all()
                if not groups:
                    print_err("none of [%s] exist in group table." % val.get('groups'),quit=True)
                obj.groups = groups
            if val.get('bind_hosts'):
                bind_hosts = common_filters.bind_hosts_filter(val)
                obj.bind_hosts = bind_hosts
            #print(obj)
            session.add(obj)
        session.commit()
예제 #2
0
파일: actions.py 프로젝트: 248808194/python
def excute_from_command_line(argvs):
    if len(argvs) < 2: #计算传入的长度,如果小于2就打印help_msg函数,并且退出
        help_msg()
        exit()
    if argvs[1] not in action_registers.actions: #如果传入的参数1 不在action_registers.actions 字典key 下  则调用utils.print_err 打印所输命令不不存在.
        utils.print_err("Command [%s] does not exist!" % argvs[1], quit=True) #
    action_registers.actions[argvs[1]](argvs[1:]) # 如果存在,获取到传入参数相对于的value函数,传入参数(参数为列表第0[程序文件名]个除外的所有参数)
예제 #3
0
def bind_group_filter(vals):
    groups = session.query(models.Group).filter(
        models.Group.name.in_(vals.get('groups'))).all()
    if not groups:
        print_err("none of [%s] exist in groups table." % vals.get('groups'),
                  quit=True)
    return groups
예제 #4
0
def create_groups(argvs):
    '''
    create 组数据
    create groups
    :param argvs:
    :return:
    '''
    if '-f' in argvs:
        group_file = argvs[argvs.index("-f") + 1]
        host_path = os.path.join(setting.BASE_DESC, group_file)
    else:
        print_err(
            "invalid usage, should be:\ncreategroups -f <the new groups file>",
            quit=True)
    source = yaml_parser(host_path)
    if source:
        for key, val in source.items():
            print(key, val)
            obj = create_table.Group(group_name=key)
            if val.get('bind_hosts'):
                bind_hosts = common_filters.bind_hosts_filter(val)
                obj.bind_hosts = bind_hosts

            if val.get('user_profiles'):
                user_profiles = common_filters.user_profiles_filter(val)
                obj.user_profiles = user_profiles
            session.add(obj)
        session.commit()
예제 #5
0
def auth():
    '''
    用户验证
    do the user.txt login authentication
    :return:
    '''
    count = 0
    while count < 3:
        username = input("\033[32;1mUsername>>>:\033[0m").strip()
        if len(username) == 0:
            continue
        password = input("\033[32;1mPassword>>>:\033[0m").strip()
        if len(password) == 0:
            continue
        user_obj = session.query(create_table.UserProfile).filter(
            create_table.UserProfile.user_name == username,
            create_table.UserProfile.password == password).first()
        if user_obj:
            return user_obj
        else:
            print("wrong username or password, you have %s more chances." %
                  (3 - count - 1))
            count += 1
    else:
        print_err("too many attempts.")
예제 #6
0
def user_profiles_filter(vals):
    user_profiles = (
        session.query(models.UserProfile).filter(models.UserProfile.username.in_(vals.get("user_profiles"))).all()
    )
    if not user_profiles:
        print_err("none of [%s] exist in user_profile table." % vals.get("user_profiles"), quit=True)
    return user_profiles
예제 #7
0
def create_bindhosts(argvs):
    '''
    create bind hosts
    :param argvs:
    :return:
    '''
    if '-f' in argvs:
        bindhosts_file = argvs[argvs.index("-f") + 1]
    else:
        print_err(
            "invalid usage, should be:\ncreate_hosts -f <the new bindhosts file>",
            quit=True)
    source = yaml_parser(bindhosts_file)
    if source:
        for key, val in source.items():
            print(key, val)
            # 获取到了主机
            host_obj = session.query(models.Host).filter(
                models.Host.hostname == val.get('hostname')).first()
            # 取hostname
            assert host_obj  # 断言,必须存在
            for item in val['remote_users']:  # 判断
                print(item)
                assert item.get('auth_type')
                if item.get('auth_type') == 'ssh-password':  # 判断认证password
                    remoteuser_obj = session.query(models.RemoteUser).filter(
                        models.RemoteUser.username == item.get('username'),
                        models.RemoteUser.password == item.get(
                            'password')).first()
                else:
                    # 获取远程用户
                    remoteuser_obj = session.query(models.RemoteUser).filter(
                        models.RemoteUser.username == item.get('username'),
                        models.RemoteUser.auth_type == item.get('auth_type'),
                    ).first()
                if not remoteuser_obj:  # 没取到,程序退出
                    print_err("RemoteUser obj %s does not exist." % item,
                              quit=True)
                bindhost_obj = models.BindHost(host_id=host_obj.id,
                                               remoteuser_id=remoteuser_obj.id)
                session.add(bindhost_obj)  # 获取到关系后添加session
                # for groups this host binds to
                if source[key].get('groups'):  # 获取组
                    group_objs = session.query(models.HostGroup).filter(
                        models.HostGroup.name.in_(
                            source[key].get('groups'))).all()
                    assert group_objs
                    print('groups:', group_objs)
                    bindhost_obj.host_groups = group_objs
                # for user_profiles this host binds to
                if source[key].get('user_profiles'):  # 判断是否直接属于哪一台机器
                    userprofile_objs = session.query(
                        models.Userprofile).filter(
                            models.Userprofile.username.in_(
                                source[key].get('user_profiles'))).all()
                    assert userprofile_objs
                    print("userprofiles:", userprofile_objs)
                    bindhost_obj.user_profiles = userprofile_objs
                # print(bindhost_obj)
        session.commit()
예제 #8
0
파일: views.py 프로젝트: shun-zi/python
def create_users(argvs):
    '''
    create little_finger access user
    :param argvs:
    :return:
    '''
    # 输入的命令行参数是否含有'-f'字符串
    if '-f' in argvs:
        # 取出文件名
        user_file = argvs[argvs.index("-f") + 1]
    else:
        # 文件不存在时,输出错误信息
        print_err(
            "invalid usage, should be:\ncreateusers -f <the new users file>",
            quit=True)
    # 得到包含用户信息的字典.
    source = yaml_parser(user_file)
    if source:
        # 一个一个的将用户存入数据库中.
        for key, val in source.items():
            print(key, val)
            obj = models.UserProfile(username=key,
                                     password=val.get('password'))
            # if val.get('groups'):
            #     groups = session.query(models.Group).filter(models.Group.name.in_(val.get('groups'))).all()
            #     if not groups:
            #         print_err("none of [%s] exist in group table." % val.get('groups'),quit=True)
            #     obj.groups = groups
            # if val.get('bind_hosts'):
            #     bind_hosts = common_filters.bind_hosts_filter(val)
            #     obj.bind_hosts = bind_hosts
            #print(obj)
            session.add(obj)
        session.commit()
예제 #9
0
def auth_student():
    '''
    用户验证
    do the user login authentication
    :return:
    '''
    count = 0
    while count < 3:
        username = input("\033[32;1mUsername:\033[0m").strip()
        if len(username) == 0:
            continue
        password = input("\033[32;1mPassword:\033[0m").strip()
        if len(password) == 0:
            continue
        user_obj = session.query(models.Student).filter(
            models.Student.username == username,
            models.Student.password == password).first()
        if user_obj:
            return user_obj
        else:
            print("wrong username or password, you have %s more chances." %
                  (3 - count - 1))
            count += 1
    else:
        print_err("too many attempts.")
예제 #10
0
def create_groups(argvs):
    """
    create groups
    :param argvs:
    :return:
    """
    if '-f' in argvs:
        group_file = argvs[argvs.index("-f") + 1]
    else:
        print_err("invalid usage, should be:\ncreategroups -f <the new groups file>", logout=True)
        return
    source = yaml_parser(group_file)
    if source:
        logger.debug("source:\n%s" % source)
        for key, val in source.items():
            logger.debug("%s:%s" % (key, val))
            obj = models.HostGroup(name=key)
            logger.info(obj)
            # if val.get('bind_hosts'):
            #     bind_hosts = common_filters.bind_hosts_filter(val)
            #     obj.bind_hosts = bind_hosts
            #
            if val.get('user_profiles'):  # 用户与主机分组关系
                user_profiles = common_filters.user_profiles_filter(val)
                obj.user_profiles = user_profiles
            session.add(obj)
        session.commit()
        logger.info("create groups sucess!")
예제 #11
0
def create_remoteusers(argvs):
    '''
    create remoteusers
    :param argvs:
    :return:
    '''
    # 里面加了判断是否是文件
    if '-f' in argvs:
        remoteusers_file = argvs[argvs.index("-f") + 1]
    else:
        print_err(
            "invalid usage, should be:\ncreate_remoteusers -f <the new remoteusers file>",
            quit=True)

    #从yaml中 load 出来
    source = yaml_parser(remoteusers_file)
    if source:
        for key, val in source.items():
            print(key, val)
            #把 yaml中load出来的值获取到,赋值给对应的 sql中表的字段
            obj = models.RemoteUser(username=val.get('username'),
                                    auth_type=val.get('auth_type'),
                                    password=val.get('password'))
            session.add(obj)
    #再提交,真正的插入数据到表中
        session.commit()
예제 #12
0
def create_users(argvs):
    """
    create user
    :param argvs:
    :return:
    """
    if '-f' in argvs:
        user_file = argvs[argvs.index("-f") + 1]
    else:
        print_err("invalid usage, should be:\ncreateusers -f <the new users file>", logout=True)
        return

    source = yaml_parser(user_file)
    if source:
        logger.debug("source:\n%s" % source)
        for key, val in source.items():
            logger.debug("%s:%s" % (key, val))
            obj = models.UserProfile(username=key, password=val.get('password'))
            logger.info(obj)
            # if val.get('groups'):
            #     groups = session.query(models.Group).filter(models.Group.name.in_(val.get('groups'))).all()
            #     if not groups:
            #         print_err("none of [%s] exist in group table." % val.get('groups'),quit=True)
            #     obj.groups = groups
            # if val.get('bind_hosts'):
            #     bind_hosts = common_filters.bind_hosts_filter(val)
            #     obj.bind_hosts = bind_hosts
            # print(obj)
            session.add(obj)
        session.commit()
        logger.info("create user sucess!")
예제 #13
0
def create_users(argvs):
    if '-f' in argvs:
        '''首先判断输入是否存在-f选项,将-f后的文件赋予user_file'''
        user_file = argvs[argvs.index("-f") + 1]
    else:
        print_err(
            "invalid usage, should be:\ncreateusers -f <the new users file>",
            quit=True)

    source = yaml_parser(user_file)
    if source:
        for key, val in source.items():
            print(key, val)
            obj = models.UserProfile(username=key,
                                     password=val.get('password'))
            if val.get('groups'):
                '''如果val中含有group,且该group存在,则同时讲该用户加入对应group'''
                groups = session.query(models.Group).filter(
                    models.Group.name.in_(val.get('groups'))).all()
                if not groups:
                    print_err("none of [%s] exist in group table." %
                              val.get('groups'),
                              quit=True)
                obj.groups = groups
            if val.get('bind_hosts'):
                '''如果val有bind_hosts,则同时绑定hosts'''
                bind_hosts = common_filters.bind_hosts_filter(val)
                obj.bind_hosts = bind_hosts
            #print(obj)
            session.add(obj)
        session.commit()
예제 #14
0
def create_hosts(argvs):
    '''
    create 主机
    :param argvs:
    :return:
    '''
    if '-f' in argvs:
        # 指定一个文件名否则报错
        hosts_file = argvs[argvs.index("-f") + 1]
        host_path = os.path.join(setting.BASE_DESC, hosts_file)
        #print('hosts_path:',host_path)
    else:
        print_err(
            "invalid usage, should be:\ncreate_hosts -f <the new hosts file>",
            quit=True)
    source = yaml_parser(host_path)  # 传文件回来
    if source:  # 循环字典
        print(source)
        for key, val in source.items():
            print(key, val)
            obj = create_table.Host(host_name=key,
                                    IP=val.get('ip'),
                                    port=val.get('port') or 22)
            # 添加到表
            try:
                session.add(obj)
            except IntegrityError as e:
                print('主机名和主机IP是唯一值已在数据库创建:', e)
            else:
                session.commit()
예제 #15
0
def excute_from_command_line(argvs):  # python bastion_host [argvs]
    if len(argvs) < 2:  # 没有带参数运行
        help_msg()
        exit()
    if argvs[1] not in action_registers.actions:  # 错误的命令参数
        utils.print_err("Command [%s] does not exist!" % argvs[1], logout=True)
    action_registers.actions[argvs[1]](argvs[1:])
예제 #16
0
def create_groups(argvs):
    '''
    create groups
    :param argvs:
    :return:
    '''
    if '-f' in argvs:
        group_file = argvs[argvs.index("-f") + 1]
    else:
        print_err(
            "invalid usage, should be:\ncreategroups -f <the new groups file>",
            quit=True)
    source = yaml_parser(group_file)
    if source:
        for key, val in source.items():
            print(key, val)
            obj = models.HostGroup(name=key)

            # if val.get('bind_hosts'):
            #     bind_hosts = common_filters.bind_hosts_filter(val)
            #     obj.bind_hosts = bind_hosts
            #
            # if val.get('user_profiles'):
            #     user_profiles = common_filters.user_profiles_filter(val)
            #     obj.user_profiles = user_profiles

            session.add(obj)
        session.commit()
예제 #17
0
def create_users(argvs):
    '''
    create little_finger access user
    :param argvs:
    :return:
    '''
    if '-f' in argvs:
        user_file  = argvs[argvs.index("-f") +1 ]
    else:
        print_err("invalid usage, should be:\ncreateusers -f <the new users file>",quit=True)

    source = yaml_parser(user_file)
    if source:
        for key,val in source.items():
            print(key,val)
            obj = models.UserProfile(username=key,password=val.get('password'))
            if val.get('groups'):
                groups = session.query(models.Group).filter(models.Group.name.in_(val.get('groups'))).all()
                if not groups:
                    print_err("none of [%s] exist in group table." % val.get('groups'),quit=True)
                obj.groups = groups
            if val.get('bind_hosts'):
                bind_hosts = common_filters.bind_hosts_filter(val)
                obj.bind_hosts = bind_hosts
            #print(obj)
            session.add(obj)
        session.commit()
예제 #18
0
def excute_from_command_line(argvs):
    if len(argvs) < 2:  #如果输入的小于2个则弹出help信息
        help_msg()
        exit()
    if argvs[1] not in action_registers.actions:  #如果输入的第一项不在我指定的操作中,则报错并退出
        utils.print_err("Command [%s] does not exist!" % argvs[1], quit=True)
    action_registers.actions[argvs[1]](argvs[1:])  #没有问题则执行
예제 #19
0
def create_groups(argv):
    '''
    create groups
    :param argv:
    :return:
    '''
    if '-f' in argv:
        group_file = argv[argv.index('-f') + 1]
    else:
        print_err(
            "Invalid usage, should be:\ncreate group -f <the new group file>",
            quit=True)
    source = yaml_parser(group_file)
    if source:
        print(source)
        for key, val in source.items():
            print(key, val)
            obj = models.HostGroup(name=key)
            if val.get('bind_host'):
                bind_hosts = common_filters.bind_hosts_filter()
                obj.bind_hosts = bind_hosts
            if val.get('user_profiles'):
                user_profiles = common_filters
                obj.user_profiles = user_profiles
            session.add(obj)
        session.commit()
예제 #20
0
def excute_from_command_line(argvs):
    if len(argvs) < 2:
        help_msg()
        exit()
    if argvs[1] not in action_registers.actions:
        utils.print_err("Command [%s] does not exist!" % argvs[1], quit=True)
    action_registers.actions[argvs[1]](argvs[1:])
예제 #21
0
def create_hosts(argvs):
    '''
    create hosts
    :param argvs:
    :return:
    '''
    if '-f' in argvs:
        hosts_file = argvs[argvs.index("-f") + 1]
    else:
        print_err(
            "invalid usage, should be:\ncreate_hosts -f <the new hosts file>",
            quit=True)
    source = yaml_parser(hosts_file)
    if source:
        for key, val in source.items():
            print(key, val)

            #models.Host 是导入进来的。是from models import models
            #把参数给models.py中的Host类中的形参
            obj = models.Host(hostname=key,
                              ip=val.get('ip'),
                              port=val.get('port') or 22)
            session.add(obj)
        #一定要提交才能真的插入进去
        session.commit()
예제 #22
0
def excute_from_command_line(argvs):
    if len(argvs) < 2:  #没有输入命令及参数,打印帮助信息,并退出
        help_msg()
        exit()
    if argvs[1] not in action_registers.actions:  #输入的命令不存在的话,就退出。
        utils.print_err("Command [%s] does not exist!" % argvs[1], quit=True)
    action_registers.actions[argvs[1]](argvs[1:])  #获取命令及参数
예제 #23
0
def excute_from_command_line(argvs):
    if len(argvs) < 2:
        help_msg()
        exit()
    if argvs[1] not in action_registers.actions:
        utils.print_err("Command [%s] does not exist!" % argvs[1], quit=True)
    action_registers.actions[argvs[1]](argvs[1:])
예제 #24
0
def user_profiles_filter(vals):
    user_profiles = session.query(models.UserProfile).filter(
        models.UserProfile.username.in_(vals.get('user_profiles'))).all()
    if not user_profiles:
        print_err("none of [%s] exist in user_profile table." %
                  vals.get('user_profiles'),
                  quit=True)
    return user_profiles
def fortress_user_filter(vals):
    fortress_users = session.query(model_v2.FortressUser).filter(
        model_v2.FortressUser.username.in_(vals.get('fortress_user'))).all()
    if not fortress_users:
        print_err("none of [%s] exist in user_profile table." %
                  vals.get('fortress_user'),
                  quit=True)
    return fortress_users
예제 #26
0
def user_profiles_filter(vals):
    jump_users = session.query(models_db.Jump_User).filter(
        models_db.Jump_User.username.in_(vals.get('jump_users'))).all()
    if not jump_users:
        print_err("none of [%s] exist in user_profile table." %
                  vals.get('jump_users'),
                  quit=True)
    return jump_users
예제 #27
0
def create_bindhosts(argvs):
    if '-f' in argvs:
        bindhosts_file = argvs[argvs.index("-f") + 1]
    else:
        print_err(
            "invalid usage, should be:\ncreate_hosts -f <the new bindhosts file>",
            quit=True)
    source = yaml_parser(bindhosts_file)
    if source:
        for key, val in source.items():
            print(key, val)
            host_obj = session.query(models.Host).filter(
                models.Host.hostname == val.get('hostname')).first()
            assert host_obj
            print(host_obj)
            '''注意下面的for语句,实际上val['remote_users']返回的是一个列表(yaml中如果有-,则变成列表),然后列表里面嵌套了字典,
            所以for其实是对列表进行了循环,而列表里面的元素则是一个个字典'''
            for item in val['remote_users']:
                print('remote_users is', item)
                '''assert断言,表示如果没有auth_type这个key,或取不到auth_type这个的值,则下面语句不执行。'''
                assert item.get('auth_type')
                if item.get('auth_type') == 'ssh-password':
                    remoteuser_obj = session.query(models.RemoteUser).filter(
                        models.RemoteUser.username == item.get('username'),
                        models.RemoteUser.password == item.get('password'),
                        #models.RemoteUser.auth_type==item.get('auth_type'),
                    ).first()
                else:
                    remoteuser_obj = session.query(models.RemoteUser).filter(
                        models.RemoteUser.username == item.get('username'),
                        models.RemoteUser.auth_type == item.get('auth_type'),
                    ).first()
                if not remoteuser_obj:
                    print_err('user [%s] is not exist' % (item), quit=True)
                bindhost_obj = models.BindHost(host_id=host_obj.id,
                                               remoteuser_id=remoteuser_obj.id)
                session.add(bindhost_obj)
                '''判断是否有groups这个字段,如果有则执行下面语句'''
                if source[key].get('groups'):
                    print(source[key].get('groups'))
                    group_objs = session.query(models.HostGroup).filter(
                        models.HostGroup.name.in_(
                            source[key].get('groups'))).all()
                    assert group_objs
                    '''通过下面语句将bind_host和host_group两个表的关联表bindhost_m2m_hostgroup建立起来,
                    将两个表相对应的主机和组的id相对应起来,实现主机和组的关联。
                    注意下面的语句将对关联表插入相关联的ID值'''
                    bindhost_obj.host_groups = group_objs

                if source[key].get('user_profiles'):
                    user_objs = session.query(models.UserProfile).filter(
                        models.UserProfile.username.in_(
                            source[key].get('user_profiles'))).all()
                    assert user_objs
                    '''通过下面的语句,将堡垒机用户表和bind_host表相关联起来,对两者的关联表user_m2m_bindhost
                    插入对应的两方id,通过该表的外键实现两表关联,最终实现用户和主机关联'''
                    bindhost_obj.user_profiles = user_objs
        session.commit()
예제 #28
0
파일: actions.py 프로젝트: sunjiebin/s12
def excute_from_command_line(argvs):
    if len(argvs) < 2:
        help_msg()
        exit()
    if argvs[1] not in action_registers.actions:
        utils.print_err("Command [%s] does not exist!" % argvs[1], quit=True)
    '''actions[argvs[1]]中通过key(argvs[1])获取到actions字典的value,再对获取的value进行调用,调用的参数为(argvs[1:])
    由于actions里面写的value是一个方法,而不是字符串,所以是能够用()调用的,argvs[1:]代表传入的第二个及以后的值作为参数'''
    action_registers.actions[argvs[1]](argvs[1:])
예제 #29
0
def create_bindhosts(argvs):
    """
    create bind hosts
    主机及该主机上的账户信息
    :param argvs:
    :return:
    """
    if '-f' in argvs:
        bindhosts_file = argvs[argvs.index("-f") + 1]
    else:
        print_err("invalid usage, should be:\ncreate_bindhosts -f <the new bindhosts file>", logout=True)
        return
    source = yaml_parser(bindhosts_file)
    if source:
        logger.debug("source:\n%s" % source)
        for key, val in source.items():
            logger.debug("%s:%s" % (key, val))
            # 要Bind的主机信息
            host_obj = session.query(models.Host).filter(models.Host.hostname == val.get('hostname')).first()
            logger.debug("host_obj---\n%s" % host_obj)
            assert host_obj
            for item in val['remote_users']:  # 要bind到该主机上的账户信息
                logger.debug(item)
                assert item.get('auth_type')
                if item.get('auth_type') == 'ssh-password':
                    remoteuser_obj = session.query(models.RemoteUser).filter(
                        models.RemoteUser.username == item.get('username'),
                        models.RemoteUser.password == item.get('password')
                    ).first()
                else:
                    remoteuser_obj = session.query(models.RemoteUser).filter(
                        models.RemoteUser.username == item.get('username'),
                        models.RemoteUser.auth_type == item.get('auth_type'),
                    ).first()
                if not remoteuser_obj:
                    print_err("RemoteUser obj %s does not exist." % item, logout=True)
                bindhost_obj = models.BindHost(host_id=host_obj.id, remoteuser_id=remoteuser_obj.id)  # 设定bind关系
                session.add(bindhost_obj)
                # for groups this host binds to 该主机bind到主机组
                if source[key].get('groups'):
                    group_objs = session.query(models.HostGroup).filter(
                        models.HostGroup.name.in_(source[key].get('groups'))).all()
                    assert group_objs
                    logger.info('groups:%s' % group_objs)
                    bindhost_obj.host_groups = group_objs
                # for user_profiles this host binds to  该主机bind到的用户
                if source[key].get('user_profiles'):
                    userprofile_objs = session.query(models.UserProfile).filter(models.UserProfile.username.in_(
                        source[key].get('user_profiles')
                    )).all()
                    logger.debug(userprofile_objs)
                    assert userprofile_objs
                    logger.info("userprofiles:%s" % userprofile_objs)
                    bindhost_obj.user_profiles = userprofile_objs
                    # print(bindhost_obj)
        session.commit()
        logger.info("create bindhosts sucess!")
예제 #30
0
def excute_from_command_line(argvs):
    #如果位置参数少于2个,就打印帮助。
    if len(argvs) < 2:
        help_msg()
        exit()
        #如果位置参数中代表的命令,不在命令列表中,就报错。
    if argvs[1] not in action_registers.actions:
        utils.print_err("Command [%s] does not exist!" % argvs[1], quit=True)
    action_registers.actions[argvs[1]](argvs[1:])
예제 #31
0
def bind_hosts_filter(vals):
    print('**>', vals.get('bind_hosts'))
    bind_hosts = session.query(models.BindHost).filter(
        models.Host.hostname.in_(vals.get('bind_hosts'))).all()
    if not bind_hosts:
        print_err("none of [%s] exist in bind_host table." %
                  vals.get('bind_hosts'),
                  quit=True)
    return bind_hosts
예제 #32
0
def groups_filter(vals):
    print('**** groups> ', vals.get('groups'))
    groups = session.query(models.Group).filter(
        models.Group.name.in_(vals.get('groups'))).all()
    if not groups:
        print_err('none of [%s] exists in group table.' % vals.get('groups'),
                  quit=True)
    else:
        return groups
예제 #33
0
def create_bindhosts(argvs):
    '''
    create bind hosts
    :param argvs:
    :return:
    '''
    if '-f' in argvs:
        bindhosts_file = argvs[argvs.index("-f") + 1]
    else:
        print_err(
            "invalid usage, should be:\ncreate_bindhosts -f <the new bindhosts file>",
            quit=True)
    source = yaml_parser(bindhosts_file)
    if source:
        for key, val in source.items():
            # print(key,val)
            host_obj = session.query(model_v2.Host).filter(
                model_v2.Host.hostname == val.get('hostname')).first()
            assert host_obj
            for item in val['remote_users']:
                print(item)
                assert item.get('auth_type')
                if item.get('auth_type') == 'ssh-password':
                    remoteuser_obj = session.query(model_v2.RemoteUser).filter(
                        model_v2.RemoteUser.username == item.get('username'),
                        model_v2.RemoteUser.password == item.get(
                            'password')).first()
                else:
                    remoteuser_obj = session.query(model_v2.RemoteUser).filter(
                        model_v2.RemoteUser.username == item.get('username'),
                        model_v2.RemoteUser.auth_type == item.get('auth_type'),
                    ).first()
                if not remoteuser_obj:
                    print_err("RemoteUser obj %s does not exist." % item,
                              quit=True)
                bindhost_obj = model_v2.BindHost(
                    host_id=host_obj.id, remoteuser_id=remoteuser_obj.id)
                session.add(bindhost_obj)
                # for groups this host binds to
                if source[key].get('groups'):
                    group_objs = session.query(model_v2.HostGroup).filter(
                        model_v2.HostGroup.name.in_(
                            source[key].get('groups'))).all()
                    assert group_objs
                    print('groups:', group_objs)
                    bindhost_obj.hostgroups = group_objs
                # for user_profiles this host binds to
                if source[key].get('fortress_user'):
                    fortressuser_objs = session.query(
                        model_v2.FortressUser).filter(
                            model_v2.FortressUser.username.in_(
                                source[key].get('fortress_user'))).all()
                    assert fortressuser_objs
                    print("fortressuser:", fortressuser_objs)
                    bindhost_obj.fortress_users = fortressuser_objs
                    # print(bindhost_obj)
        session.commit()
예제 #34
0
def create_hosts(argvs):
    """根据yml文件创建host表中的数据"""
    if '-f' in argvs:
        hosts_file = argvs[argvs.index("-f") + 1]
    else:
        print_err("invalid usage, should be:\ncreate_hosts -f <the new hosts file>", quit=True)
    source = yaml_parser(hosts_file)  # 解析yml文件为对象
    if source:
        # print(source)
        for key, val in source.items():
            print(key, val)
            obj = models_v2.Host(hostname=key, ip=val.get('ip'), port=val.get('port') or 22)  # 创建一行host数据
            session.add(obj)
        session.commit()
예제 #35
0
def create_remoteusers(argvs):
    """根据yml文件创建remote_user表中的数据"""
    if '-f' in argvs:
        remoteusers_file = argvs[argvs.index("-f") + 1]
    else:
        print_err("invalid usage, should be:\ncreate_remoteusers -f <the new remoteusers file>", quit=True)
    source = yaml_parser(remoteusers_file)
    if source:
        for key, val in source.items():
            print(key, val)
            obj = models_v2.RemoteUser(username=val.get('username'), auth_type=val.get('auth_type'),
                                       password=val.get('password'))
            session.add(obj)
        session.commit()
예제 #36
0
def create_bindhosts(argvs):
    '''
    create bind hosts
    :param argvs:
    :return:
    '''
    if '-f' in argvs:
        bindhosts_file  = argvs[argvs.index("-f") +1 ]
    else:
        print_err("invalid usage, should be:\ncreate_hosts -f <the new bindhosts file>",quit=True)
    source = yaml_parser(bindhosts_file)
    if source:
        for key,val in source.items():
            #print(key,val)
            host_obj = session.query(models.Host).filter(models.Host.hostname==val.get('hostname')).first()
            assert host_obj
            for item in val['remote_users']:
                print(item )
                assert item.get('auth_type')
                if item.get('auth_type') == 'ssh-passwd':
                    remoteuser_obj = session.query(models.RemoteUser).filter(
                                                        models.RemoteUser.username==item.get('username'),
                                                        models.RemoteUser.password==item.get('password')
                                                    ).first()
                else:
                    remoteuser_obj = session.query(models.RemoteUser).filter(
                                                        models.RemoteUser.username==item.get('username'),
                                                        models.RemoteUser.auth_type==item.get('auth_type'),
                                                    ).first()
                if not remoteuser_obj:
                    print_err("RemoteUser obj %s does not exist." % item,quit=True )
                bindhost_obj = models.BindHost(host_id=host_obj.id,remoteuser_id=remoteuser_obj.id)
                session.add(bindhost_obj)
                #for groups this host binds to
                if source[key].get('groups'):
                    group_objs = session.query(models.Group).filter(models.Group.name.in_(source[key].get('groups') )).all()
                    assert group_objs
                    print('groups:', group_objs)
                    bindhost_obj.groups = group_objs
                #for user_profiles this host binds to
                if source[key].get('user_profiles'):
                    userprofile_objs = session.query(models.UserProfile).filter(models.UserProfile.username.in_(
                        source[key].get('user_profiles')
                    )).all()
                    assert userprofile_objs
                    print("userprofiles:",userprofile_objs)
                    bindhost_obj.user_profiles = userprofile_objs
                #print(bindhost_obj)
        session.commit()
예제 #37
0
def create_hosts(argvs):
    '''
    create hosts
    :param argvs:
    :return:
    '''
    if '-f' in argvs:
        hosts_file  = argvs[argvs.index("-f") +1 ]
    else:
        print_err("invalid usage, should be:\ncreate_hosts -f <the new hosts file>",quit=True)
    source = yaml_parser(hosts_file)
    if source:
        for key,val in source.items():
            print(key,val)
            obj = models.Host(hostname=key,ip_addr=val.get('ip_addr'), port=val.get('port') or 22)
            session.add(obj)
        session.commit()
예제 #38
0
def create_bindhosts(argvs):
    """根据yml文件创建BindHost表中的数据"""
    if '-f' in argvs:
        bindhosts_file = argvs[argvs.index("-f") + 1]
    else:
        print_err("invalid usage, should be:\ncreate_hosts -f <the new bindhosts file>", quit=True)
    source = yaml_parser(bindhosts_file)
    if source:
        for key, val in source.items():
            # print(key,val)
            host_obj = session.query(models_v2.Host).filter(models_v2.Host.hostname == val.get('hostname')).first()
            assert host_obj  # 断言是否存在这个主机, 如果没有抛出异常不向下执行
            for item in val['remote_users']:
                print(item)
                assert item.get('auth_type')
                if item.get('auth_type') == 'ssh-passwd':
                    remoteuser_obj = session.query(models_v2.RemoteUser).filter(
                        models_v2.RemoteUser.username == item.get('username'),
                        models_v2.RemoteUser.password == item.get('password')
                    ).first()
                else:
                    remoteuser_obj = session.query(models_v2.RemoteUser).filter(
                        models_v2.RemoteUser.username == item.get('username'),
                        models_v2.RemoteUser.auth_type == item.get('auth_type'),
                    ).first()
                if not remoteuser_obj:  # 如果RemoteUser表不存在bindhost.yml文件中的remoteUser, 抛出异常
                    print_err("RemoteUser obj %s does not exist." % item, quit=True)
                bindhost_obj = models_v2.BindHost(host_id=host_obj.id, remoteuser_id=remoteuser_obj.id)
                session.add(bindhost_obj)
                # for groups this host binds to
                if source[key].get('groups'):
                    # select * from HostGroup where name in (bjgroup, shgroup);
                    group_objs = session.query(models_v2.HostGroup).filter(
                        models_v2.HostGroup.name.in_(source[key].get('groups'))).all()
                    assert group_objs  # 断言
                    bindhost_obj.host_groups = group_objs
                # for user_profiles this host binds to
                if source[key].get('user_profiles'):
                    userprofile_objs = session.query(models_v2.UserProfile).filter(models_v2.UserProfile.username.in_(
                        source[key].get('user_profiles')
                    )).all()
                    assert userprofile_objs  # 断言
                    print("userprofiles:", userprofile_objs)
                    bindhost_obj.user_profiles = userprofile_objs
                    # print(bindhost_obj)
        session.commit()
예제 #39
0
def auth():
    """ start session中用户认证操作 """
    count = 0
    while count < 3:
        username = input("\033[32;1mUsername:\033[0m").strip()
        if len(username) == 0:
            continue
        password = input("\033[32;1mPassword:\033[0m").strip()
        if len(password) == 0:
            continue
        user_obj = session.query(models_v2.UserProfile).filter(models_v2.UserProfile.username == username,
                                                               models_v2.UserProfile.password == password).first()
        if user_obj:
            return user_obj
        else:
            print("wrong username or password, you have %s more chances." % (3 - count - 1))
            count += 1
    else:
        print_err("too many attempts.")
예제 #40
0
def create_groups(argvs):
    """根据yml文件创建Group表中的数据"""
    if '-f' in argvs:
        group_file = argvs[argvs.index("-f") + 1]
    else:
        print_err("invalid usage, should be:\ncreategroups -f <the new groups file>", quit=True)
    source = yaml_parser(group_file)
    if source:
        for key, val in source.items():
            print(key, val)
            obj = models_v2.HostGroup(name=key)
            # if val.get('bind_hosts'):
            #     bind_hosts = common_filters.bind_hosts_filter(val)
            #     obj.bind_hosts = bind_hosts
            #
            # if val.get('user_profiles'):
            #     user_profiles = common_filters.user_profiles_filter(val)
            #     obj.user_profiles = user_profiles
            session.add(obj)
        session.commit()
예제 #41
0
def auth():
    '''
    do the user login authentication
    :return:
    '''
    count = 0
    while count <3:
        username = raw_input("\033[32;1mUsername:\033[0m").strip()
        if len(username) ==0:continue
        password = raw_input("\033[32;1mPassword:\033[0m").strip()
        if len(password) ==0:continue
        user_obj = session.query(models.UserProfile).filter(models.UserProfile.username==username,
                                                            models.UserProfile.password==password).first()
        if user_obj:
            return user_obj
        else:
            print("wrong username or password, you have %s more chances." %(3-count-1))
            count +=1
    else:
        print_err("too many attempts.")
예제 #42
0
def create_users(argvs):
    """根据yml文件创建堡垒机user表中的数据"""
    if '-f' in argvs:
        user_file = argvs[argvs.index("-f") + 1]
    else:
        print_err("invalid usage, should be:\ncreateusers -f <the new users file>", quit=True)

    source = yaml_parser(user_file)
    if source:
        for key, val in source.items():
            print(key, val)
            obj = models_v2.UserProfile(username=key, password=val.get('password'))
            # if val.get('groups'):
            #     groups = session.query(models_v2.Group).filter(models_v2.Group.name.in_(val.get('groups'))).all()
            #     if not groups:
            #         print_err("none of [%s] exist in group table." % val.get('groups'), quit=True)
            #     obj.groups = groups
            # if val.get('bind_hosts'):
            #     bind_hosts = common_filters.bind_hosts_filter(val)
            #     obj.bind_hosts = bind_hosts
            # # print(obj)
            session.add(obj)
        session.commit()
예제 #43
0
def create_groups(argvs):
    '''
    create groups
    :param argvs:
    :return:
    '''
    if '-f' in argvs:
        group_file  = argvs[argvs.index("-f") +1 ]
    else:
        print_err("invalid usage, should be:\ncreategroups -f <the new groups file>",quit=True)
    source = yaml_parser(group_file)
    if source:
        for key,val in source.items():
            print(key,val)
            obj = models.Group(name=key)
            if val.get('bind_hosts'):
                bind_hosts = common_filters.bind_hosts_filter(val)
                obj.bind_hosts = bind_hosts

            if val.get('user_profiles'):
                user_profiles = common_filters.user_profiles_filter(val)
                obj.user_profiles = user_profiles
            session.add(obj)
        session.commit()
예제 #44
0
def bind_hosts_filter(vals):
    print("**>", vals.get("bind_hosts"))
    bind_hosts = session.query(models.BindHost).filter(models.Host.hostname.in_(vals.get("bind_hosts"))).all()
    if not bind_hosts:
        print_err("none of [%s] exist in bind_host table." % vals.get("bind_hosts"), quit=True)
    return bind_hosts