使用 python 从 ansible tower 获取 OAuth2 令牌?

Getting OAuth2 token from ansible tower with python?

我正在尝试 get/create 使用此 python 脚本的 OAuth2 访问令牌:

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/."}'

更新二:

好的,此代码获取令牌:

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 令牌。

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'))

生成令牌后,将其添加到请求中即可用于其他请求 header Authorization: Bearer <oauth2-token-value>.

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

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