在Python中获取Google Compute Engine实例的IP地址的最简单方法是什么?

时间:2014-02-07 00:23:56

标签: python google-compute-engine

如果我知道实例的区域和名称,获取实例的公共IP地址的最简单方法是什么?

def get_public_ip(region, instance_name):
    # ???

2 个答案:

答案 0 :(得分:2)

使用gcutil:

$ gcutil listinstances --columns=external-ip

或使用python api networkInterfaces结构如下:

u'networkInterfaces':[
  {
     u'accessConfigs':[
        {
           u'kind':u'compute#accessConfig',
           u'type':u'ONE_TO_ONE_NAT',
           u'name':u'External NAT',
           u'natIP':u'xxx.xxx.xxx.xxx'
        }
     ],
     u'networkIP':u'10.xxx.xxx.xxx',
     u'network': u'https://www.googleapis.com/compute/v1/projects/<my-project-id>/global/networks/<network-name>',
     u'name':u'nic0'
  }

因此您可以使用this Listing Instances example执行以下操作:

for instance in instances:
    print instance['networkInterfaces'][0]['accessConfigs'][0]['natIP']

答案 1 :(得分:0)

试试这个:

credentials = GoogleCredentials.get_application_default()
api = build('compute', 'v1', credentials=credentials)

response = api.instances().get(project=project_id, zone=region, instance=instance_name).execute()

ip = response['networkInterfaces'][0]['accessConfigs'][0]['natIP']

返回计算引擎前端列出的外部IP