Python 如何获取在Google云上运行的计算引擎实例数
在Google Cloud文档中,获取在Google Cloud中的项目上运行的实例的列表和数量的命令行如下所示:Python 如何获取在Google云上运行的计算引擎实例数,python,google-cloud-platform,google-compute-engine,Python,Google Cloud Platform,Google Compute Engine,在Google Cloud文档中,获取在Google Cloud中的项目上运行的实例的列表和数量的命令行如下所示: gcloud compute instances list 或 如何使用Google Cloud获得Python中的等效函数?这里有相关文档: 简言之: import googleapiclient.discovery project="your project" zone="your zone" compute = googleapi
gcloud compute instances list
或
如何使用Google Cloud获得Python中的等效函数?这里有相关文档: 简言之:
import googleapiclient.discovery
project="your project"
zone="your zone"
compute = googleapiclient.discovery.build('compute', 'v1')
instances = compute.instances().list(project=project, zone=zone).execute()
for instance in instances:
print(' - ' + instance['name'])
这里有关于这方面的文件: 简言之:
import googleapiclient.discovery
project="your project"
zone="your zone"
compute = googleapiclient.discovery.build('compute', 'v1')
instances = compute.instances().list(project=project, zone=zone).execute()
for instance in instances:
print(' - ' + instance['name'])
下面是我编写的一个示例,它使用RESTAPI而不使用Google Cloud SDK 本例将向您介绍服务帐户、授权、访问令牌和计算引擎RESTAPI的底层细节
'''
This program lists lists the Google Compute Engine Instances in one zone
'''
import time
import json
import jwt
import requests
import httplib2
# Project ID for this request.
project = 'development-123456'
# The name of the zone for this request.
zone = 'us-west1-a'
# Service Account Credentials, Json format
json_filename = 'service-account.json'
# Permissions to request for Access Token
scopes = "https://www.googleapis.com/auth/cloud-platform"
# Set how long this token will be valid in seconds
expires_in = 3600 # Expires in 1 hour
def load_json_credentials(filename):
''' Load the Google Service Account Credentials from Json file '''
with open(filename, 'r') as f:
data = f.read()
return json.loads(data)
def load_private_key(json_cred):
''' Return the private key from the json credentials '''
return json_cred['private_key']
def create_signed_jwt(pkey, pkey_id, email, scope):
'''
Create a Signed JWT from a service account Json credentials file
This Signed JWT will later be exchanged for an Access Token
'''
# Google Endpoint for creating OAuth 2.0 Access Tokens from Signed-JWT
auth_url = "https://www.googleapis.com/oauth2/v4/token"
issued = int(time.time())
expires = issued + expires_in # expires_in is in seconds
# Note: this token expires and cannot be refreshed. The token must be recreated
# JWT Headers
additional_headers = {
'kid': pkey_id,
"alg": "RS256",
"typ": "JWT" # Google uses SHA256withRSA
}
# JWT Payload
payload = {
"iss": email, # Issuer claim
"sub": email, # Issuer claim
"aud": auth_url, # Audience claim
"iat": issued, # Issued At claim
"exp": expires, # Expire time
"scope": scope # Permissions
}
# Encode the headers and payload and sign creating a Signed JWT (JWS)
sig = jwt.encode(payload, pkey, algorithm="RS256", headers=additional_headers)
return sig
def exchangeJwtForAccessToken(signed_jwt):
'''
This function takes a Signed JWT and exchanges it for a Google OAuth Access Token
'''
auth_url = "https://www.googleapis.com/oauth2/v4/token"
params = {
"grant_type": "urn:ietf:params:oauth:grant-type:jwt-bearer",
"assertion": signed_jwt
}
r = requests.post(auth_url, data=params)
if r.ok:
return(r.json()['access_token'], '')
return None, r.text
def gce_list_instances(accessToken):
'''
This functions lists the Google Compute Engine Instances in one zone
'''
# Endpoint that we will call
url = "https://www.googleapis.com/compute/v1/projects/" + project + "/zones/" + zone + "/instances"
# One of the headers is "Authorization: Bearer $TOKEN"
headers = {
"Host": "www.googleapis.com",
"Authorization": "Bearer " + accessToken,
"Content-Type": "application/json"
}
h = httplib2.Http()
resp, content = h.request(uri=url, method="GET", headers=headers)
status = int(resp.status)
if status < 200 or status >= 300:
print('Error: HTTP Request failed')
return
j = json.loads(content.decode('utf-8').replace('\n', ''))
print('Compute instances in zone', zone)
print('------------------------------------------------------------')
for item in j['items']:
print(item['name'])
if __name__ == '__main__':
cred = load_json_credentials(json_filename)
private_key = load_private_key(cred)
s_jwt = create_signed_jwt(
private_key,
cred['private_key_id'],
cred['client_email'],
scopes)
token, err = exchangeJwtForAccessToken(s_jwt)
if token is None:
print('Error:', err)
exit(1)
gce_list_instances(token)
“”
此程序在一个区域中列出Google计算引擎实例
'''
导入时间
导入json
进口jwt
导入请求
导入httplib2
#此请求的项目ID。
项目='development-123456'
#此请求的区域的名称。
区域='us-west1-a'
#服务帐户凭据,Json格式
json_filename='service account.json'
#请求访问令牌的权限
作用域=”https://www.googleapis.com/auth/cloud-platform"
#设置此令牌的有效时间(秒)
expires_in=3600#1小时后过期
def load_json_凭据(文件名):
''从Json文件''加载Google服务帐户凭据'
将open(filename,'r')作为f:
data=f.read()
返回json.loads(数据)
def load_private_key(json_cred):
''从json凭据返回私钥''
返回json_cred['private_key']
def create_signed_jwt(pkey、pkey_id、电子邮件、范围):
'''
从服务帐户Json凭据文件创建签名JWT
该签名JWT稍后将被交换为访问令牌
'''
#用于从签名JWT创建OAuth 2.0访问令牌的Google端点
验证url=”https://www.googleapis.com/oauth2/v4/token"
已发布=int(time.time())
expires=已发布+过期(以秒为单位)
#注意:此令牌过期,无法刷新。必须重新创建令牌
#JWT头
其他_头={
“孩子”:pkey_id,
“alg”:“RS256”,
“类型”:“JWT”#谷歌将SHA256与RSA一起使用
}
#JWT有效载荷
有效载荷={
“iss”:电子邮件,#发行人索赔
“sub”:电子邮件,#发行人索赔
“aud”:授权url,#观众声明
“iat”:签发,#在索赔时签发
“exp”:过期,#过期时间
“范围”:范围#权限
}
#对报头和有效负载进行编码并签名创建签名JWT(JWS)
sig=jwt.encode(有效载荷,pkey,algorithm=“RS256”,头文件=附加的头文件)
返回信号
def exchangeJwtForAccessToken(已签名):
'''
此函数获取签名JWT并将其交换为Google OAuth访问令牌
'''
验证url=”https://www.googleapis.com/oauth2/v4/token"
参数={
“授权类型”:“urn:ietf:params:oauth:grant-type:jwt-bearer”,
“断言”:签名的jwt
}
r=requests.post(auth_url,data=params)
如果r.ok:
返回(r.json()['access_token'],'')
返回None,r.text
def gce_列表_实例(accessToken):
'''
此函数在一个区域中列出Google计算引擎实例
'''
#我们将调用的端点
url=”https://www.googleapis.com/compute/v1/projects/“+project+”/zones/“+zone+”/instances”
#其中一个标题是“Authorization:Bearer$TOKEN”
标题={
“主持人”:“www.googleapis.com”,
“授权”:“持票人”+accessToken,
“内容类型”:“应用程序/json”
}
h=httplib2.Http()
resp,content=h.request(uri=url,method=“GET”,headers=headers)
状态=整数(对应状态)
如果状态<200或状态>=300:
打印('错误:HTTP请求失败')
返回
j=json.load(content.decode('utf-8')。replace('\n','')
打印('区域中的计算实例',区域)
打印('---------------------------------------------------------------')
对于j['items']中的项目:
打印(项目['name'])
如果uuuu name uuuuuu='\uuuuuuu main\uuuuuuu':
cred=load_json_凭证(json_文件名)
私钥=加载私钥(cred)
s_jwt=创建_签名的_jwt(
私钥,
cred['private_key_id'],
cred[“客户电子邮件”],
范围)
令牌,err=exchangeJwtForAccessToken(s_jwt)
如果令牌为无:
打印('错误:',错误)
出口(1)
gce_列表_实例(令牌)
下面是我编写的一个示例,它使用RESTAPI而不使用Google Cloud SDK
本例将向您介绍服务帐户、授权、访问令牌和计算引擎RESTAPI的底层细节
'''
This program lists lists the Google Compute Engine Instances in one zone
'''
import time
import json
import jwt
import requests
import httplib2
# Project ID for this request.
project = 'development-123456'
# The name of the zone for this request.
zone = 'us-west1-a'
# Service Account Credentials, Json format
json_filename = 'service-account.json'
# Permissions to request for Access Token
scopes = "https://www.googleapis.com/auth/cloud-platform"
# Set how long this token will be valid in seconds
expires_in = 3600 # Expires in 1 hour
def load_json_credentials(filename):
''' Load the Google Service Account Credentials from Json file '''
with open(filename, 'r') as f:
data = f.read()
return json.loads(data)
def load_private_key(json_cred):
''' Return the private key from the json credentials '''
return json_cred['private_key']
def create_signed_jwt(pkey, pkey_id, email, scope):
'''
Create a Signed JWT from a service account Json credentials file
This Signed JWT will later be exchanged for an Access Token
'''
# Google Endpoint for creating OAuth 2.0 Access Tokens from Signed-JWT
auth_url = "https://www.googleapis.com/oauth2/v4/token"
issued = int(time.time())
expires = issued + expires_in # expires_in is in seconds
# Note: this token expires and cannot be refreshed. The token must be recreated
# JWT Headers
additional_headers = {
'kid': pkey_id,
"alg": "RS256",
"typ": "JWT" # Google uses SHA256withRSA
}
# JWT Payload
payload = {
"iss": email, # Issuer claim
"sub": email, # Issuer claim
"aud": auth_url, # Audience claim
"iat": issued, # Issued At claim
"exp": expires, # Expire time
"scope": scope # Permissions
}
# Encode the headers and payload and sign creating a Signed JWT (JWS)
sig = jwt.encode(payload, pkey, algorithm="RS256", headers=additional_headers)
return sig
def exchangeJwtForAccessToken(signed_jwt):
'''
This function takes a Signed JWT and exchanges it for a Google OAuth Access Token
'''
auth_url = "https://www.googleapis.com/oauth2/v4/token"
params = {
"grant_type": "urn:ietf:params:oauth:grant-type:jwt-bearer",
"assertion": signed_jwt
}
r = requests.post(auth_url, data=params)
if r.ok:
return(r.json()['access_token'], '')
return None, r.text
def gce_list_instances(accessToken):
'''
This functions lists the Google Compute Engine Instances in one zone
'''
# Endpoint that we will call
url = "https://www.googleapis.com/compute/v1/projects/" + project + "/zones/" + zone + "/instances"
# One of the headers is "Authorization: Bearer $TOKEN"
headers = {
"Host": "www.googleapis.com",
"Authorization": "Bearer " + accessToken,
"Content-Type": "application/json"
}
h = httplib2.Http()
resp, content = h.request(uri=url, method="GET", headers=headers)
status = int(resp.status)
if status < 200 or status >= 300:
print('Error: HTTP Request failed')
return
j = json.loads(content.decode('utf-8').replace('\n', ''))
print('Compute instances in zone', zone)
print('------------------------------------------------------------')
for item in j['items']:
print(item['name'])
if __name__ == '__main__':
cred = load_json_credentials(json_filename)
private_key = load_private_key(cred)
s_jwt = create_signed_jwt(
private_key,
cred['private_key_id'],
cred['client_email'],
scopes)
token, err = exchangeJwtForAccessToken(s_jwt)
if token is None:
print('Error:', err)
exit(1)
gce_list_instances(token)
“”
此程序在一个区域中列出Google计算引擎实例
'''
导入时间
导入json
进口jwt
导入请求
导入httplib2
#此请求的项目ID。
项目='development-123456'
#此请求的区域的名称。
区域='us-west1-a'
#服务帐户凭据,Json格式
json_filename='service account.json'
#请求访问令牌的权限
作用域=”https://www.googleapis.com/auth/cloud-platform"
#设置此令牌的有效时间(秒)
expires_in=3600#1小时后过期
def load_json_凭据(文件名):
''从Json文件''加载Google服务帐户凭据'
将open(filename,'r')作为f:
data=f.read()
返回json.loads(数据)
def load_private_key(json_cred):
''从json凭据返回私钥''
返回json_cred['private_key']
def create_signed_jwt(pkey、pkey_id、电子邮件、范围):
'''
从服务帐户Json凭据文件创建签名JWT
该签名JWT稍后将被交换为访问令牌
'''
#用于从签名JWT创建OAuth 2.0访问令牌的Google端点
验证url=”https://www.googleapis.com/oauth2/v4/token"
已发布=int(time.time)