1

我想通过https://gcr.io http API 从 Google Cloud Docker Registry 中检索图像列表。

我找到了一种从命令行执行此操作的方法,如下所示:

curl -u _token:$(gcloud auth print-access-token) https://gcr.io/v2/{project}/{repo}/tags/list

但我想在 Python 中以编程方式完成它。这是我到目前为止所尝试的:

下面的工作,但我找不到不调用gcloudshell cmd 来检索身份验证令牌的方法。

import requests
import subprocess

command = "gcloud auth print-access-token"
pswd= subprocess.check_output(command, shell=True).decode().strip()

repo = "repo"
project = "myproject"
user = "_token"
url = "https://gcr.io/v2/{project}/{repo}/tags/list".format(project=project, repo=repo)
r = requests.get(url, auth=(user, pswd))
print (r.status_code, r.headers['content-type'], r.encoding, r.text)

此外,我还尝试使用经过身份验证的 httplib2 执行请求:

import httplib2
from oauth2client.client import GoogleCredentials
http = httplib2.Http()
credentials = GoogleCredentials.get_application_default()

scopes = "https://www.googleapis.com/auth/cloud-platform"

credentials = credentials.create_scoped(scopes)

http = credentials.authorize(http)
print (http.request("https://gcr.io/v2/healthshield-dev/dl/tags/list"))

结果是b'{"errors":[{"code":"UNAUTHORIZED","message":"Not Authorized."}]}'

有人可以和我分享他在这方面的经验吗?

4

1 回答 1

0

我能够在这里完成您需要做的事情,但是在 Java 中,转换为 Python 应该相当简单。这就是我所做的:

  1. 使用适用于 Java 的 Google OAuth2 API 客户端库 ( https://developers.google.com/identity/protocols/OAuth2ServiceAccount#authorizingrequests ) 获取用于对 gcr.io/v2 请求进行身份验证的令牌。“其他”部分,我为服务帐户使用了 jsonKeyFile 设置。

Python 客户端库 -> https://developers.google.com/api-client-library/python/guide/aaa_oauth

        GoogleCredential credential = GoogleCredential.fromStream(keyFileInputStream).createScoped(Collections.singleton(ContainerScopes.CLOUD_PLATFORM));

        credential.refreshToken();
        String token = credential.getAccessToken();
  1. 现在使用令牌,只需向https://gcr.io/v2/xxxx/tags/list发出 GET 请求

请注意,使用 curl -u 您将凭据作为 _token:value 传递,因此您需要将其编码为您需要在请求中设置的基本身份验证标头。这就是我所做的(有点):

String encoding = Base64Encoder.encode("_token:"+token);
HttpHeaders headers = new HttpHeaders();
headers.set("Authorization", "Basic " + encoding);

希望这可以帮助。

于 2016-04-15T22:03:36.440 回答