Esempio n. 1
0
def main():
    request_options = TSC.RequestOptions(pagesize=1000)
    content = fwapi()
    # tableau_auth = TSC.TableauAuth('20040201', 'GT2020!qaz', site_id='')
    tableau_auth = TSC.TableauAuth('GT_Account', 'GT2020123456', site_id='')
    server = TSC.Server('https://fas-gt.com:8000', use_server_version=True)
    # server = TSC.Server('https://tab.sucgm.com:10000')
    infos = content['data']
    print(infos)
    connect = sqlcon()
    cursor = connect.cursor()  # 创建一个游标对象,python里的sql语句都要通过cursor来执行
    allgroup = []
    for info in infos:
        # 遍历获取群组id和群组名称
        groupid = info['id']
        groupname = info['rolesmark']  # 获取群组名称
        groupname = groupname[:-5]  # 将群组名称后的 -致同群组 字段删除
        allgroup.append([groupid, groupname])

        # sql = "select GroupName from OFW_GROUP_TAB_ALLOWED where IsDelete = 0 and GroupId = %s"
        sql = "select GroupName from OFW_GROUP_TAB_ALLOWED_TEST where IsDelete = 0 and GroupId = %s"
        cursor.execute(sql, groupid)
        row = cursor.fetchall()  # 读取查询结果,
        # print(row)
        rowCount = len(row)
        if rowCount == 0:
            # sql = "insert into OFW_GROUP_TAB_ALLOWED (GroupId,GroupName) VALUES (%s,%s)"
            sql = "insert into OFW_GROUP_TAB_ALLOWED_TEST (GroupId,GroupName) VALUES (%s,%s)"
            value = (groupid, groupname)
            cursor.execute(sql, value)
            # 提交到数据库执行
            connect.commit()
            with server.auth.sign_in(tableau_auth):
                newgroup = TSC.GroupItem(groupname)
                newgroup = server.groups.create(newgroup)
                # print(newgroup.name)
            print('群组' + groupname + '添加成功')
        else:
            rawdata = row[0][0]
            if rawdata != groupname:
                print('群组' + rawdata + '名称需要修改')
                with server.auth.sign_in(tableau_auth):
                    # 通过TSM  修改user对应群组
                    all_groups, pagination_item = server.groups.get(
                        request_options)
                    for group in all_groups:
                        if group.name == rawdata:
                            group.name = groupname
                            newg = server.groups.update(group)
                            break

                # sql = "Update OFW_GROUP_TAB_ALLOWED SET GroupName = %s where GroupId =%s"
                sql = "Update OFW_GROUP_TAB_ALLOWED_TEST SET GroupName = %s where GroupId =%s"
                value = (groupname, groupid)
                cursor.execute(sql, value)
                # 提交到数据库执行
                connect.commit()
                print("完成对 " + groupname + " 群组名称的更改")
            else:
                print('已存在' + groupname + ',无需更改')
Esempio n. 2
0
    def create_group(self, group_name):
        """ Create a new group for the given server and site.

            PARAMETERS
            -----
            group_name : STRING
                The name of the new group.

            RETURNS
            -----
            GROUP_ITEM

        """

        sites_switched = False

        if self.id != self.__server.current_site.id:
            self.__server.switch_current_site(self)
            sites_switched = True

        new_group = tsc.GroupItem(group_name)
        new_group = self.__server.item.groups.create(new_group)
        new_group = groupItem.Group_Item(self.__server, new_group)

        self.__groups.append(new_group)

        if sites_switched is True:
            self.__server.switch_current_site(self.__server.previous_site)

        return new_group
def main():

    parser = argparse.ArgumentParser(
        description='Creates sample schedules for each type of frequency.')
    parser.add_argument('--server', '-s', required=True, help='server address')
    parser.add_argument('--username',
                        '-u',
                        required=True,
                        help='username to sign into server')
    parser.add_argument('--logging-level',
                        '-l',
                        choices=['debug', 'info', 'error'],
                        default='error',
                        help='desired logging level (set to error by default)')
    args = parser.parse_args()

    password = getpass.getpass("Password: ")

    # Set logging level based on user input, or error by default
    logging_level = getattr(logging, args.logging_level.upper())
    logging.basicConfig(level=logging_level)

    tableau_auth = TSC.TableauAuth(args.username, password)
    server = TSC.Server(args.server)
    with server.auth.sign_in(tableau_auth):
        group = TSC.GroupItem('test')
        group = server.groups.create(group)
        print(group)
    def test_delete_permission(self) -> None:
        with open(asset(POPULATE_PERMISSIONS_XML), "rb") as f:
            response_xml = f.read().decode("utf-8")
        with requests_mock.mock() as m:
            m.get(self.baseurl +
                  "/0448d2ed-590d-4fa0-b272-a2a8a24555b5/permissions",
                  text=response_xml)

            single_group = TSC.GroupItem("Group1")
            single_group._id = "c8f2773a-c83a-11e8-8c8f-33e6d787b506"

            single_project = TSC.ProjectItem("Project3")
            single_project._id = "0448d2ed-590d-4fa0-b272-a2a8a24555b5"

            self.server.projects.populate_permissions(single_project)
            permissions = single_project.permissions

            capabilities = {}

            for permission in permissions:
                if permission.grantee.tag_name == "group":
                    if permission.grantee.id == single_group._id:
                        capabilities = permission.capabilities

            rules = TSC.PermissionsRule(grantee=single_group.to_reference(),
                                        capabilities=capabilities)

            endpoint = "{}/permissions/groups/{}".format(
                single_project._id, single_group._id)
            m.delete("{}/{}/Read/Allow".format(self.baseurl, endpoint),
                     status_code=204)
            m.delete("{}/{}/Write/Allow".format(self.baseurl, endpoint),
                     status_code=204)
            self.server.projects.delete_permission(item=single_project,
                                                   rules=rules)
Esempio n. 5
0
    def _sync_site_groups(self):
        self.logger.debug('Revision groups on site')
        ad_site_groups = [
            g.name.value for g in self.ad.get_site_groups(self.site_name)
        ]
        tableau_site_groups = [g.name for g in TSC.Pager(self.tab.groups)]
        new_groups = set(ad_site_groups) - set(tableau_site_groups)
        old_groups = set(tableau_site_groups) - set(ad_site_groups)
        old_groups.remove('All Users')
        # This ugly code, but I was forced to write this.
        if self.site_name == 'ERS':
            self.logger.info(f"Site ERS. Remove from old_groups F_* and A_*")
            old_groups = [
                t for t in old_groups
                if not (t.startswith('F_') or t.startswith('A_'))
            ]
        # End ugly code

        if new_groups:
            self.logger.info("New groups {0}".format(new_groups))
        if old_groups:
            self.logger.info("Old groups {0}".format(old_groups))
        for group in new_groups:
            new_group = TSC.GroupItem(group)
            self.logger.info(f"Creating group {group}")
            if self.noop:
                self.tab.groups.create(new_group)
        for group in old_groups:
            group_id = [
                g.id for g in TSC.Pager(self.tab.groups) if g.name == group
            ].pop()
            self.logger.info(f"Removing group {group}")
            if self.noop:
                self.tab.groups.delete(group_id)
Esempio n. 6
0
    def test_delete_permission(self):
        with open(asset(POPULATE_PERMISSIONS_XML), 'rb') as f:
            response_xml = f.read().decode('utf-8')
        with requests_mock.mock() as m:
            m.get(self.baseurl + '/0448d2ed-590d-4fa0-b272-a2a8a24555b5/permissions', text=response_xml)

            single_group = TSC.GroupItem('Group1')
            single_group._id = 'c8f2773a-c83a-11e8-8c8f-33e6d787b506'

            single_project = TSC.ProjectItem('Project3')
            single_project._id = '0448d2ed-590d-4fa0-b272-a2a8a24555b5'

            self.server.projects.populate_permissions(single_project)
            permissions = single_project.permissions

            capabilities = {}

            for permission in permissions:
                if permission.grantee.tag_name == "group":
                    if permission.grantee.id == single_group._id:
                        capabilities = permission.capabilities

            rules = TSC.PermissionsRule(
                grantee=single_group,
                capabilities=capabilities
            )

            endpoint = '{}/permissions/groups/{}'.format(single_project._id, single_group._id)
            m.delete('{}/{}/Read/Allow'.format(self.baseurl, endpoint), status_code=204)
            m.delete('{}/{}/Write/Allow'.format(self.baseurl, endpoint), status_code=204)
            self.server.projects.delete_permission(item=single_project, rules=rules)
Esempio n. 7
0
    def test_update_datasource_default_permission(self):
        response_xml = read_xml_asset(UPDATE_DATASOURCE_DEFAULT_PERMISSIONS_XML)
        with requests_mock.mock() as m:
            m.put(self.baseurl + '/b4065286-80f0-11ea-af1b-cb7191f48e45/default-permissions/datasources',
                  text=response_xml)
            project = TSC.ProjectItem('test-project')
            project._id = 'b4065286-80f0-11ea-af1b-cb7191f48e45'

            group = TSC.GroupItem('test-group')
            group._id = 'b4488bce-80f0-11ea-af1c-976d0c1dab39'

            capabilities = {TSC.Permission.Capability.ExportXml: TSC.Permission.Mode.Deny}

            rules = [TSC.PermissionsRule(
                grantee=group,
                capabilities=capabilities
            )]

            new_rules = self.server.projects.update_datasource_default_permissions(project, rules)

        self.assertEquals('b4488bce-80f0-11ea-af1c-976d0c1dab39', new_rules[0].grantee.id)

        updated_capabilities = new_rules[0].capabilities
        self.assertEquals(4, len(updated_capabilities))
        self.assertEquals('Deny', updated_capabilities['ExportXml'])
        self.assertEquals('Allow', updated_capabilities['Read'])
        self.assertEquals('Allow', updated_capabilities['Write'])
        self.assertEquals('Allow', updated_capabilities['Connect'])
Esempio n. 8
0
    def test_remove_user(self) -> None:
        with open(POPULATE_USERS, "rb") as f:
            response_xml_populate = f.read().decode("utf-8")

        with open(POPULATE_USERS_EMPTY, "rb") as f:
            response_xml_empty = f.read().decode("utf-8")

        with requests_mock.mock() as m:
            url = self.baseurl + "/e7833b48-c6f7-47b5-a2a7-36e7dd232758/users" "/dd2239f6-ddf1-4107-981a-4cf94e415794"

            m.delete(url, status_code=204)
            #  We register the get endpoint twice. The first time we have 1 user, the second we have 'removed' them.
            m.get(self.baseurl + "/e7833b48-c6f7-47b5-a2a7-36e7dd232758/users",
                  text=response_xml_populate)

            single_group = TSC.GroupItem("test")
            single_group._id = "e7833b48-c6f7-47b5-a2a7-36e7dd232758"
            self.server.groups.populate_users(single_group)
            self.assertEqual(1, len(list(single_group.users)))
            self.server.groups.remove_user(
                single_group, "dd2239f6-ddf1-4107-981a-4cf94e415794")

            m.get(self.baseurl + "/e7833b48-c6f7-47b5-a2a7-36e7dd232758/users",
                  text=response_xml_empty)
            self.assertEqual(0, len(list(single_group.users)))
def automatically_create_users(users_to_import,
                               tableau_token_value='',
                               tableau_token_name='datadev',
                               tableau_content_url='chrishastieiwdev598367'):
    import tableauserverclient as tsc
    import getpass

    # Request user password if not provided already
    if tableau_token_value == '':
        import getpass
        tableau_token_value = getpass.getpass('Access token:')

    tableau_auth = tsc.PersonalAccessTokenAuth(tableau_token_name,
                                               tableau_token_value,
                                               tableau_content_url)
    server = tsc.Server('https://10ax.online.tableau.com/',
                        use_server_version=True)

    with server.auth.sign_in(tableau_auth):
        for user in users_to_import:
            group_item = check_if_group_exists(server, user['group'])
            if not group_item:
                new_group = tsc.GroupItem(user['group'])
                group_item = server.groups.create(new_group)

            user_item = check_if_user_exists(server, user['email'])
            if not user_item:
                new_user = tsc.UserItem(user['email'], 'Unlicensed')
                user_item = server.users.add(new_user)

            server.groups.add_user(group_item, user_item.id)
def addgroup(groupname):
    # create a new instance with the group name
    # 添加群组
    newgroup = TSC.GroupItem(groupname)

    # call the create method
    newgroup = server.groups.create(newgroup)
Esempio n. 11
0
def main():

    parser = argparse.ArgumentParser(description='Creates a sample user group.')
    # Common options; please keep those in sync across all samples
    parser.add_argument('--server', '-s', required=True, help='server address')
    parser.add_argument('--site', '-S', help='site name')
    parser.add_argument('--token-name', '-p', required=True,
                        help='name of the personal access token used to sign into the server')
    parser.add_argument('--token-value', '-v', required=True,
                        help='value of the personal access token used to sign into the server')
    parser.add_argument('--logging-level', '-l', choices=['debug', 'info', 'error'], default='error',
                        help='desired logging level (set to error by default)')
    # Options specific to this sample
    # This sample has no additional options, yet. If you add some, please add them here

    args = parser.parse_args()

    # Set logging level based on user input, or error by default
    logging_level = getattr(logging, args.logging_level.upper())
    logging.basicConfig(level=logging_level)

    tableau_auth = TSC.PersonalAccessTokenAuth(args.token_name, args.token_value, site_id=args.site)
    server = TSC.Server(args.server, use_server_version=True)
    with server.auth.sign_in(tableau_auth):
        group = TSC.GroupItem('test')
        group = server.groups.create(group)
        print(group)
    def test_update_local_async(self):
        group = TSC.GroupItem("myGroup")
        group._id = 'ef8b19c0-43b6-11e6-af50-63f5805dbe3c'
        self.assertRaises(ValueError, self.server.groups.update, group, as_job=True)

        # mimic group returned from server where domain name is set to 'local'
        group.domain_name = "local"
        self.assertRaises(ValueError, self.server.groups.update, group, as_job=True)
def create_example_group(group_name="Example Group", server=None):
    new_group = TSC.GroupItem(group_name)
    try:
        new_group = server.groups.create(new_group)
        print("Created a new project called: '%s'" % group_name)
        print(new_group)
    except TSC.ServerResponseError:
        print("Group '%s' already existed" % group_name)
Esempio n. 14
0
 def test_remove_user_missing_group_id(self) -> None:
     single_group = TSC.GroupItem("test")
     self.assertRaises(
         TSC.MissingRequiredFieldError,
         self.server.groups.remove_user,
         single_group,
         "5de011f8-5aa9-4d5b-b991-f462c8dd6bb7",
     )
Esempio n. 15
0
def create_example_group(group_name='Example Group', server=None):
    new_group = TSC.GroupItem(group_name)
    try:
        new_group = server.groups.create(new_group)
        print('Created a new project called: \'%s\'' % group_name)
        print(new_group)
    except TSC.ServerResponseError:
        print('Group \'%s\' already existed' % group_name)
Esempio n. 16
0
 def test_create_group(self) -> None:
     with open(CREATE_GROUP, "rb") as f:
         response_xml = f.read().decode("utf-8")
     with requests_mock.mock() as m:
         m.post(self.baseurl, text=response_xml)
         group_to_create = TSC.GroupItem("試供品")
         group = self.server.groups.create(group_to_create)
         self.assertEqual(group.name, "試供品")
         self.assertEqual(group.id, "3e4a9ea0-a07a-4fe6-b50f-c345c8c81034")
Esempio n. 17
0
    def test_invalid_name(self):
        self.assertRaises(ValueError, TSC.GroupItem, None)
        self.assertRaises(ValueError, TSC.GroupItem, "")
        group = TSC.GroupItem("grp")
        with self.assertRaises(ValueError):
            group.name = None

        with self.assertRaises(ValueError):
            group.name = ""
Esempio n. 18
0
 def test_create_group(self):
     with open(CREATE_GROUP, 'rb') as f:
         response_xml = f.read().decode('utf-8')
     with requests_mock.mock() as m:
         m.post(self.baseurl, text=response_xml)
         group_to_create = TSC.GroupItem(u'試供品')
         group = self.server.groups.create(group_to_create)
         self.assertEqual(group.name, u'試供品')
         self.assertEqual(group.id, '3e4a9ea0-a07a-4fe6-b50f-c345c8c81034')
Esempio n. 19
0
 def test_create_group_async(self) -> None:
     with open(CREATE_GROUP_ASYNC, "rb") as f:
         response_xml = f.read().decode("utf-8")
     with requests_mock.mock() as m:
         m.post(self.baseurl, text=response_xml)
         group_to_create = TSC.GroupItem("試供品")
         group_to_create.domain_name = "woohoo"
         job = self.server.groups.create_AD_group(group_to_create, True)
         self.assertEqual(job.mode, "Asynchronous")
         self.assertEqual(job.type, "GroupImport")
 def test_create_group_async(self):
     with open(CREATE_GROUP_ASYNC, 'rb') as f:
         response_xml = f.read().decode('utf-8')
     with requests_mock.mock() as m:
         m.post(self.baseurl, text=response_xml)
         group_to_create = TSC.GroupItem(u'試供品')
         group_to_create.domain_name = 'woohoo'
         job = self.server.groups.create_AD_group(group_to_create, True)
         self.assertEqual(job.mode, 'Asynchronous')
         self.assertEqual(job.type, 'GroupImport')
    def test_remove_user_missing_user_id(self):
        with open(POPULATE_USERS, 'rb') as f:
            response_xml = f.read().decode('utf-8')
        with requests_mock.mock() as m:
            m.get(self.baseurl + '/e7833b48-c6f7-47b5-a2a7-36e7dd232758/users', text=response_xml)
            single_group = TSC.GroupItem(name='Test Group')
            single_group._id = 'e7833b48-c6f7-47b5-a2a7-36e7dd232758'
            self.server.groups.populate_users(single_group)

        self.assertRaises(ValueError, self.server.groups.remove_user, single_group, '')
 def test_create_ad_group(self):
     with open(CREATE_GROUP_AD, 'rb') as f:
         response_xml = f.read().decode('utf-8')
     with requests_mock.mock() as m:
         m.post(self.baseurl, text=response_xml)
         group_to_create = TSC.GroupItem(u'試供品')
         group_to_create.domain_name = 'just-has-to-exist'
         group = self.server.groups.create_AD_group(group_to_create, False)
         self.assertEqual(group.name, u'試供品')
         self.assertEqual(group.license_mode, 'onLogin')
         self.assertEqual(group.minimum_site_role, 'Creator')
         self.assertEqual(group.domain_name, 'active-directory-domain-name')
    def test_update(self):
        with open(UPDATE_XML, 'rb') as f:
            response_xml = f.read().decode('utf-8')
        with requests_mock.mock() as m:
            m.put(self.baseurl + '/ef8b19c0-43b6-11e6-af50-63f5805dbe3c', text=response_xml)
            group = TSC.GroupItem(name='Test Group')
            group._domain_name = 'local'
            group._id = 'ef8b19c0-43b6-11e6-af50-63f5805dbe3c'
            group = self.server.groups.update(group)

        self.assertEqual('ef8b19c0-43b6-11e6-af50-63f5805dbe3c', group.id)
        self.assertEqual('Group updated name', group.name)
Esempio n. 24
0
 def test_create_ad_group(self) -> None:
     with open(CREATE_GROUP_AD, "rb") as f:
         response_xml = f.read().decode("utf-8")
     with requests_mock.mock() as m:
         m.post(self.baseurl, text=response_xml)
         group_to_create = TSC.GroupItem("試供品")
         group_to_create.domain_name = "just-has-to-exist"
         group = self.server.groups.create_AD_group(group_to_create, False)
         self.assertEqual(group.name, "試供品")
         self.assertEqual(group.license_mode, "onLogin")
         self.assertEqual(group.minimum_site_role, "Creator")
         self.assertEqual(group.domain_name, "active-directory-domain-name")
Esempio n. 25
0
    def test_remove_user_missing_user_id(self) -> None:
        with open(POPULATE_USERS, "rb") as f:
            response_xml = f.read().decode("utf-8")
        with requests_mock.mock() as m:
            m.get(self.baseurl + "/e7833b48-c6f7-47b5-a2a7-36e7dd232758/users",
                  text=response_xml)
            single_group = TSC.GroupItem(name="Test Group")
            single_group._id = "e7833b48-c6f7-47b5-a2a7-36e7dd232758"
            self.server.groups.populate_users(single_group)

        self.assertRaises(ValueError, self.server.groups.remove_user,
                          single_group, "")
Esempio n. 26
0
    def test_update(self) -> None:
        with open(UPDATE_XML, "rb") as f:
            response_xml = f.read().decode("utf-8")
        with requests_mock.mock() as m:
            m.put(self.baseurl + "/ef8b19c0-43b6-11e6-af50-63f5805dbe3c",
                  text=response_xml)
            group = TSC.GroupItem(name="Test Group")
            group._domain_name = "local"
            group._id = "ef8b19c0-43b6-11e6-af50-63f5805dbe3c"
            group = self.server.groups.update(group)

        self.assertEqual("ef8b19c0-43b6-11e6-af50-63f5805dbe3c", group.id)
        self.assertEqual("Group updated name", group.name)
        self.assertEqual("ExplorerCanPublish", group.minimum_site_role)
        self.assertEqual("onLogin", group.license_mode)
Esempio n. 27
0
 def run_command(args):
     logger = log(__class__.__name__, args.logging_level)
     logger.debug(_("tabcmd.launching"))
     session = Session()
     server = session.create_session(args)
     try:
         logger.info(_("creategroup.status").format(args.name))
         new_group = TSC.GroupItem(args.name)
         server.groups.create(new_group)
         logger.info(_("tabcmd.result.succeeded"))
     except TSC.ServerResponseError as e:
         if args.continue_if_exists and Errors.is_resource_conflict(e):
             logger.info(_("tabcmd.result.already_exists.group").format(args.name))
             return
         Errors.exit_with_error(logger, "tabcmd.result.failed.create_group")
Esempio n. 28
0
    def test_populate_users(self):
        with open(POPULATE_USERS, 'rb') as f:
            response_xml = f.read().decode('utf-8')
        with requests_mock.mock() as m:
            m.get(self.baseurl + '/e7833b48-c6f7-47b5-a2a7-36e7dd232758/users',
                  text=response_xml)
            single_group = TSC.GroupItem(name='Test Group')
            single_group._id = 'e7833b48-c6f7-47b5-a2a7-36e7dd232758'
            pagination_item = self.server.groups.populate_users(single_group)

        self.assertEqual(1, pagination_item.total_available)
        user = single_group.users.pop()
        self.assertEqual('dd2239f6-ddf1-4107-981a-4cf94e415794', user.id)
        self.assertEqual('alice', user.name)
        self.assertEqual('Publisher', user.site_role)
        self.assertEqual('2016-08-16T23:17:06Z', user.last_login)
    def test_populate_users(self):
        with open(POPULATE_USERS, 'rb') as f:
            response_xml = f.read().decode('utf-8')
        with requests_mock.mock() as m:
            m.get(self.baseurl + '/e7833b48-c6f7-47b5-a2a7-36e7dd232758/users?pageNumber=1&pageSize=100',
                  text=response_xml, complete_qs=True)
            single_group = TSC.GroupItem(name='Test Group')
            single_group._id = 'e7833b48-c6f7-47b5-a2a7-36e7dd232758'
            self.server.groups.populate_users(single_group)

            self.assertEqual(1, len(list(single_group.users)))
            user = list(single_group.users).pop()
            self.assertEqual('dd2239f6-ddf1-4107-981a-4cf94e415794', user.id)
            self.assertEqual('alice', user.name)
            self.assertEqual('Publisher', user.site_role)
            self.assertEqual('2016-08-16T23:17:06Z', format_datetime(user.last_login))
Esempio n. 30
0
    def test_remove_user(self):
        with open(POPULATE_USERS, 'rb') as f:
            response_xml = f.read().decode('utf-8')
        with requests_mock.mock() as m:
            url = self.baseurl + '/e7833b48-c6f7-47b5-a2a7-36e7dd232758/users' \
                                 '/dd2239f6-ddf1-4107-981a-4cf94e415794'
            m.delete(url, status_code=204)
            m.get(self.baseurl + '/e7833b48-c6f7-47b5-a2a7-36e7dd232758/users',
                  text=response_xml)
            single_group = TSC.GroupItem('test')
            single_group._id = 'e7833b48-c6f7-47b5-a2a7-36e7dd232758'
            self.server.groups.populate_users(single_group)
            self.assertEqual(1, len(single_group.users))
            self.server.groups.remove_user(
                single_group, 'dd2239f6-ddf1-4107-981a-4cf94e415794')

        self.assertEqual(0, len(single_group.users))