钉钉与阿里云RAM账户删除自动化脚本
概述
本脚本用于通过钉钉获取用户的电子邮件前缀,并在阿里云RAM中对该用户的AccessKey和RAM控制台登录权限进行管理。脚本自动检查用户是否存在AccessKey,如果存在,则禁用该用户的RAM Web控制台登录权限;如果不存在,则删除该用户的RAM账户。
功能说明
- 获取钉钉AccessToken:脚本首先通过钉钉API获取访问令牌(AccessToken)。
- 获取钉钉用户信息:使用上述AccessToken,通过钉钉API获取指定用户的电子邮件前缀(如果存在)。
- 管理阿里云RAM账户:
- 检查该用户在阿里云RAM中的AccessKey列表。
- 如果存在AccessKey,则禁用该用户的RAM Web控制台登录权限。
- 如果不存在AccessKey,则删除该用户的RAM账户。
使用说明
先决条件
- 钉钉开发者权限:你需要拥有钉钉应用的AppKey和AppSecret,才能通过API获取AccessToken。
- 阿里云账户权限:需要阿里云RAM管理权限,并设置环境变量
ALIBABA_CLOUD_ACCESS_KEY_ID和ALIBABA_CLOUD_ACCESS_KEY_SECRET。
环境配置
- Python版本要求:
Python 3.6及以上 - 依赖库:
alibabacloud_ram20150501alibabacloud_tea_openapialibabacloud_tea_utildingtalk
你可以通过以下命令安装依赖库:
pip install alibabacloud_ram20150501 alibabacloud_tea_openapi alibabacloud_tea_util dingtalk-py
```python
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# This file is auto-generated, don't edit it. Thanks.
import os
import sys
import asyncio
from typing import List
import dingtalk.api
from alibabacloud_ram20150501.client import Client as Ram20150501Client
from alibabacloud_tea_openapi import models as open_api_models
from alibabacloud_ram20150501 import models as ram_20150501_models
from alibabacloud_tea_util import models as util_models
from alibabacloud_tea_util.client import Client as UtilClient
def get_access_token():
req = dingtalk.api.OapiGettokenRequest("https://oapi.dingtalk.com/gettoken")
req.appkey = "your_appkey_here" # Replace with your actual appkey
req.appsecret = "your_appsecret_here" # Replace with your actual appsecret
try:
resp = req.getResponse()
access_token = resp.get('access_token')
return access_token
except Exception as e:
print(e)
access_token = get_access_token()
req = dingtalk.api.OapiV2UserGetRequest("https://oapi.dingtalk.com/topapi/v2/user/get")
req.userid = "your_userid_here" # Replace with the actual user ID
try:
resp = req.getResponse(access_token)
if 'email' in resp['result'] and resp['result']['email']: # Check if email exists and is not empty
email = resp['result']['email'] # Extract email
prefix = email.split('@')[0] # Extract prefix
print("name : ", prefix) # Print prefix
else:
print("The user does not have an email")
except Exception as e:
print(e)
username = prefix
class Sample:
def __init__(self):
pass
@staticmethod
def create_client(
access_key_id: str,
access_key_secret: str,
) -> Ram20150501Client:
config = open_api_models.Config(
access_key_id=access_key_id,
access_key_secret=access_key_secret
)
config.endpoint = f'ram.aliyuncs.com'
return Ram20150501Client(config)
@staticmethod
async def main_async(
args: List[str],
) -> None:
client = Sample.create_client(os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID'], os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET'])
list_access_keys_request = ram_20150501_models.ListAccessKeysRequest(
user_name=username
)
runtime = util_models.RuntimeOptions()
try:
response = await client.list_access_keys_with_options_async(list_access_keys_request, runtime)
# Extract AccessKey list
access_keys = response.body.access_keys.access_key
# Check if the list is not empty
if access_keys:
# Print the first AccessKeyId value
print("Current user's AccessKey is: " + access_keys[0].access_key_id + "\nDisabling RAM web console login")
# If AccessKeyId exists, disable RAM user's web console login
delete_login_profile_request = ram_20150501_models.DeleteLoginProfileRequest(
user_name=username
)
await client.delete_login_profile_with_options_async(delete_login_profile_request, runtime)
else:
print("No AccessKey found. Deleting " + username + " RAM user")
# If no AccessKeyId exists, proceed to delete the RAM user
delete_user_request = ram_20150501_models.DeleteUserRequest(
user_name=username
)
await client.delete_user_with_options_async(delete_user_request, runtime)
except Exception as error:
if '404' in str(error) or 'EntityNotExist.User' in str(error):
print("RAM account for the user not found")
else:
raise error
if __name__ == '__main__':
loop = asyncio.get_event_loop()
loop.run_until_complete(Sample.main_async(sys.argv[1:]))
评论区