openstack-api-manage/keystone/user.py

71 lines
2.3 KiB
Python
Raw Normal View History

2024-06-07 10:16:54 +08:00
import requests
import json
def create_user(ip, token, user_name, password, description):
headers = {'X-Auth-Token': token}
body = {
"user": {
"name": user_name,
"password": password,
"description": description,
}
}
resp = requests.post(f"http://{ip}:5000/v3/users", data=json.dumps(body), headers=headers)
2024-06-07 15:08:22 +08:00
return resp.json()
2024-06-07 10:16:54 +08:00
def get_users(ip, token):
headers = {'X-Auth-Token': token}
resp = requests.get(f"http://{ip}:5000/v3/users", headers=headers)
2024-06-07 15:08:22 +08:00
return resp.json()
2024-06-07 10:16:54 +08:00
def get_user_id(ip, token, user_name):
headers = {'X-Auth-Token': token}
result = requests.get(f"http://{ip}:5000/v3/users", headers=headers).json()
for item in result['users']:
if item['name'] == user_name:
return item['id']
2024-06-07 15:08:22 +08:00
else:
return None
2024-06-07 10:16:54 +08:00
def get_user(ip, token, user_name):
user_id = get_user_id(ip, token, user_name)
if user_id == "NONE":
2024-06-07 15:08:22 +08:00
return {"error": "用户不存在"}
2024-06-07 10:16:54 +08:00
headers = {'X-Auth-Token': token}
api_url = f"http://{ip}:5000/v3/users/{user_id}"
resp = requests.get(api_url, headers=headers)
2024-06-07 15:08:22 +08:00
return resp.json()
2024-06-07 10:16:54 +08:00
def delete_user(ip, token, user_name):
user_id = get_user_id(ip, token, user_name)
if user_id == "NONE":
2024-06-07 15:08:22 +08:00
return {"error": "用户不存在"}
2024-06-07 10:16:54 +08:00
headers = {'X-Auth-Token': token}
api_url = f"http://{ip}:5000/v3/users/{user_id}"
resp = requests.delete(api_url, headers=headers)
if resp.status_code == 204:
return {"message":"用户删除成功"}
else:
return {"error": "用户删除失败", "status_code": resp.status_code}
def update_user_password(ip, token, user_name, new_password, original_password):
user_id = get_user_id(ip, token, user_name)
if user_id == "NONE":
return {"error": "User not found"}
headers = {'X-Auth-Token': token}
body = {
"user": {
"password": new_password,
"original_password": original_password
}
}
api_url = f"http://{ip}:5000/v3/users/{user_id}/password"
resp = requests.post(api_url, data=json.dumps(body), headers=headers)
if resp.status_code == 204:
return {"message": "密码更新成功"}
else:
return {"error": "密码更新失败", "status_code": resp.status_code}