gpt4 book ai didi

ansible-tower - 使用python从ansible Tower获取OAuth2 token ?

转载 作者:行者123 更新时间:2023-12-04 10:38:08 24 4
gpt4 key购买 nike

我正在尝试使用此 python 脚本获取/创建 OAuth2 访问 token :

import requests
import json

token_url = 'https://mytower.example.com/api/v2/tokens/'

data = {
"description": "My Access Token",
"application": 2,
"scope": "write"
}

client_id = "I457Uue7...Ikdiafhjd"
client_secret = "Xvcgsh8...Ikadfi84"

user = 'myaccount'
passwd = 'that works in the UI'
# Get token
params = {"grant_type": "password", "username": user, "password": passwd}
headers = {"Content-Type": "application/x-www-form-urlencoded"}
response = requests.post(token_url, auth=(client_id, client_secret), headers=headers, params=params, verify=False)
print(f'{response.status_code} {response.content}')
if response.status_code == 200:
token = response.json()['access_token']
print(token)

当我运行脚本时,我收到此错误:
401 b'{"detail":"Authentication credentials were not provided. To establish a login session, visit /api/login/."}'

我看过这里的文档: https://docs.ansible.com/ansible-tower/latest/html/administration/oauth2_token_auth.html但我想不通。

请帮忙

更新:

当我执行此 python 代码时:
import requests
import json

token_url = 'https://mytower.example.com/api/v2/tokens/'

headers = {"Content-Type": "application/json"}

user = 'me'
passwd = 'mypasswd'

# Get token
response = requests.post(token_url, verify=False, auth=(user, passwd))
print(f'{response.status_code} {response.content}')
token = response.json()['access_token']
print(token)

我得到这个输出:
401 b'{"detail":"Authentication credentials were not provided. To establish a login session, visit /api/login/."}'

更新二:

好的,此代码获取 token :
import requests

token_url = 'https://mytower.example.com/api/v2/tokens/'

data = {
"description": "My Access Token",
"application": 2,
"scope": "write"
}

headers = { 'Content-Type': 'application/json' }
gen_user = 'me'
gen_pass = 'mypassword'

# Get token
response = requests.post(token_url, auth=(gen_user, gen_pass), headers=headers, json=data, verify=False)
print(f'{response.status_code} {response.content}')

最佳答案

根据官方文档。
您可以使用以下 curl 命令创建 OAuth 2 token 。

curl -u user:password -k -X POST https://<tower-host>/api/v2/tokens/

可以使用请求包将其转换为 Python

import requests

response = requests.post('https://<tower-host>/api/v2/tokens/',
verify=False, auth=('user', 'password'))

生成 token 后,可以通过将其添加到请求 header Authorization: Bearer <oauth2-token-value> 中来将其用于其他请求。 .

引用 : https://www.ansible.com/blog/summary-of-authentication-methods-in-red-hat-ansible-tower

更新:
您将数据作为 json 传递并设置 header 的 Content-Type属性(property)到 application/x-www-form-urlencoded ,应该是 application/json .

关于ansible-tower - 使用python从ansible Tower获取OAuth2 token ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60068378/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com