自动化创建ETX用户帐号

在芯片设计行业,ETX是常见的远程访问环境。用户在通过ETX访问远程环境前必须首先加入ETX系统,然后通过profile分配相关的环境的访问权限。

通常这些操作在ETX WEB页面手工操作,如果我们期望实现用户帐号注册全自动化,就需要将以上操作通过脚本来实现。

经过调查发现ETX提供了REST访问接口,因此帐号注册全自动化就可以实现。

主要流程如下:

在调用ETX REST接口前还需要获取ETX API的URL以及访问密钥。登录ETX后,点击右上部用户头像旁边的齿轮图标,在用户设置中选择创建 API keys即可生成ETX API访问密钥。

ETX登录界面左上角选择 REST API即可显示所有ETX API,点击还可查看API的详细说明和示例。

通过 Python 自动创建ETX帐号的示例代码如下:

python 复制代码
#!/opt/miniconda3/bin/python
################################################################################
#
# Author: Shuguangbo
#
################################################################################

import traceback
import logging
import logging.config
import urllib3
import requests
import json

urllib3.disable_warnings()

class userHandler():
    def __init__(self):
        self._account = ''
        self._userID = ''
        self._etxUserID = ''
        self.getETXGroup()
        ...
        
    def getETXUserID(self):
        session = None
        userData = dict()
        userID = ''
        account = self._account
        try:
            apiurl = self._config['ETX']['ETX_URL'] + f'/etx/api/v2/users?where_login={account}'
            session = requests.Session()
            header = {'Content-Type': 'application/json', 'Authorization': f"ETX {self._config['ETX']['API_KEY']}"}
            result = session.get(apiurl, headers=header, verify=False)
            
            if result.status_code == 200:
                logging.info('Get ETX user ID succeeded.')
                userList = json.loads(result.text)
                userID = userList[0]['id']
                self._etxUserID = userID
            else:
                logging.error('Get ETX user ID failed.')
        except Exception as e:
            logging.error(f"Get ETX user ID failed. error: {str(e)}, stack: {traceback.format_exc()}")
        finally:
            if session:
                session.close()
        return userID

    def getETXGroup(self):
        groupData = dict()
        session = None
        try:
            apiurl = self._config['ETX']['ETX_URL'] + '/etx/api/v2/usergroups'
            session = requests.Session()
            header = {'Content-Type': 'application/json', 'Authorization': f"ETX {self._config['ETX']['API_KEY']}"}
            result = session.get(apiurl, headers=header, verify=False)
            if result.status_code == 200:
                logging.info('Get ETX group info succeeded.')
                groupList = json.loads(result.text)
                for group in groupList:
                    groupData[group['name']] = group
            else:
                logging.error(f'Get ETX group info failed. Error: {result.text}')
                exit(1)

        except Exception as e:
            logging.error(f"GET ETX user group info failed. error: {str(e)}, stack: {traceback.format_exc()}")
            exit(1)
        finally:
            if session:
                session.close()
        self._etxGroups = groupData

    def addETXUserIntoGroup(self, userID, groupID):
        result = True
        session = None
        try:
            apiurl = self._config['ETX']['ETX_URL'] + f'/etx/api/v2/usergroups/{groupID}/members/addbyid/{userID}'
            session = requests.Session()
            header = {'Content-Type': 'application/json', 'Authorization': f"ETX {self._config['ETX']['API_KEY']}"}
            result = session.post(apiurl, headers=header, verify=False)
            if result and result.status_code == 200:
                logging.info(f'Add user {userID} into ETX group {groupID} succeeded.')
            else:
                logging.error(f'Add user {userID} into ETX group {groupID} failed.')
                result = False
        except Exception as e:
            logging.error(f"Add ETX user into user group failed. error: {str(e)}, stack: {traceback.format_exc()}")
            result = False
        finally:
            if session:
                session.close()
        return result


    def registerETXUser(self):
        EMSG = ''
        session = None
        try:
            account = self._account
            name = self._name
            email = self._email
            apiurl = self._config['ETX']['ETX_URL'] + '/etx/api/v2/users'
            session = requests.Session()
            header = {'Content-Type': 'application/json', 'Authorization': f"ETX {self._config['ETX']['API_KEY']}"}
            data = {'login': account, 'name': name, 'email': email, 'role':{'name':'User'}}
            result = session.post(apiurl, headers=header, data=json.dumps(data), verify=False)
            if result and result.status_code == 200:
                userData = json.loads(result.text)
                self._etxUserID = userData['id']
                logging.info(f'Register ETX user {account} succeeded. User id: {userData["id"]}')
            else:
                logging.error(f'Register ETX user {account} failed. Error: {result.text}')
                EMSG = f"Register ETX user {account} failed."
        except Exception as e:
            logging.error(f"Register ETX user {account} failed. Error: {str(e)}")
            EMSG = f"Register ETX user {account} failed."
        finally:
            if session:
                session.close()
        return EMSG
        
    def addETXUser(self):
        EMSG = ''
        try:
            user = self._account

            ret = self._registerETXUser()
            if len(ret):
                EMSG += ret
                return EMSG

            userID = self._etxUserID
            if len(userID) == 0:
                EMSG = "ETX user id is invalid.\n"
                return EMSG

            etxgroup = self._config['ETX']['DEFAULT_GROUP']                     
            groupID = self._etxGroups[etxgroup]['id']
            ret = self.addETXUserIntoGroup(userID, groupID)
            if not ret:
                EMSG += f'Failed to add ETX profile for {user} .\n'             

        except Exception as e:
            logging.error(f"Add ETX User profile failed. error: {str(e)}, stack: {traceback.format_exc()}"
            EMSG += "Add ETX User profile failed.\n"
        return EMSG
相关推荐
魔道不误砍柴功2 分钟前
Java 中如何巧妙应用 Function 让方法复用性更强
java·开发语言·python
_.Switch27 分钟前
高级Python自动化运维:容器安全与网络策略的深度解析
运维·网络·python·安全·自动化·devops
测开小菜鸟2 小时前
使用python向钉钉群聊发送消息
java·python·钉钉
萧鼎3 小时前
Python并发编程库:Asyncio的异步编程实战
开发语言·数据库·python·异步
学地理的小胖砸3 小时前
【一些关于Python的信息和帮助】
开发语言·python
疯一样的码农3 小时前
Python 继承、多态、封装、抽象
开发语言·python
Python大数据分析@3 小时前
python操作CSV和excel,如何来做?
开发语言·python·excel
黑叶白树3 小时前
简单的签到程序 python笔记
笔记·python
Shy9604184 小时前
Bert完形填空
python·深度学习·bert
上海_彭彭4 小时前
【提效工具开发】Python功能模块执行和 SQL 执行 需求整理
开发语言·python·sql·测试工具·element