使用 Google Compute API 作为服务器自动化

Using Google Compute API automated over as server

我正在为 Python 使用 Google 客户端 API 库。我的代码是 运行 在 Ubuntu 14.04LTS 服务器上。

我有一个正在运行的 Google 计算项目,我创建并下载了一个 OAuth2.0 令牌到我的服务器。

我正在尝试编写执行以下操作的脚本:

  1. 自动(无需用户交互)向 Google 计算引擎进行身份验证。
  2. 创建一个新的 VM,然后执行更多操作...

我的基本问题是使用 OAuth2.0 身份验证。它需要用户在 javascript 支持的浏览器上批准,我想在我的服务器上自动完成。

在我的桌面上使用我的代码是可行的。弹出一个浏览器页面需要我的批准。在我的服务器上,我收到以下消息:

we have detected that your javascript is disabled in your browser

我用于认证的代码段是:

# authenticate using the OAuth token                                
client_secret = os.path.join(
     os.path.dirname(__file__),
     self._oauth_token_path)
# set up a Flow object for the authentication                                           
flow = client.flow_from_clientsecrets(
     client_secret,
     scope=scope,
     message=tools.message_if_missing(client_secret))
# open credential storage path                                                          
credential_storage = file.Storage(self._credential_storage_path)
credentials = credential_storage.get()
# get credentails if necessary                                                          
if credentials is None or credentials.invalid:
credentials = tools.run_flow(flow, credential_storage, flags)

我阅读了有关服务帐户访问以替代常规 OAuth2.0 身份验证的内容。有谁知道这是否是最好的方法?关于如何做得更好有什么想法吗?

OAuth 2.0 需要用户批准,如果您想 运行 您的 code/scripts 自动,则不适合使用该方法。 服务帐户更适合这种情况,并且受 API (https://cloud.google.com/compute/docs/authentication#tools) 支持 您在开发人员控制台中创建一个服务帐户 + 密钥,并使用两者来验证您的应用程序。