python 使用公共DNS区域中的主机名自动更新计算引擎实例IP

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python 使用公共DNS区域中的主机名自动更新计算引擎实例IP相关的知识,希望对你有一定的参考价值。

#!/usr/bin/python
import httplib2
import urllib
import json
import sys

from apiclient.discovery import build
from oauth2client import client as oauth2_client

# PREREQUISITE
# apt-get update && apt-get -y install python-pip
# pip install --upgrade google-api-python-client

METADATA_SERVER = 'http://metadata/computeMetadata/v1/instance/service-accounts'
IP_META = 'http://metadata/computeMetadata/v1/instance/network-interfaces/0/access-configs/0/external-ip'
HOST_META = 'http://metadata/computeMetadata/v1/instance/hostname'
SCOPE = 'https://www.googleapis.com/auth/ndev.clouddns.readwrite'
PROJECT_META = 'http://metadata/computeMetadata/v1/project/project-id'
SERVICE_ACCOUNT = 'default'
# === YOU NEED TO CHANGE THESE TWO ===
DNS_ZONE_NAME = 'gecho'
DNS_DOMAIN_NAME = 'sub.eegecho.com'

def service_auth():
  http = httplib2.Http()
  token_uri = '%s/%s/token' % (METADATA_SERVER, SERVICE_ACCOUNT)
  resp, content = http.request(token_uri, method='GET',
                               body=None,
                               headers={'Metadata-Flavor': 'Google'})
  if resp.status == 200:
      d = json.loads(content)
      access_token = d['access_token']  # Save the access token
      credentials = oauth2_client.AccessTokenCredentials(d['access_token'],
                                                         'my-user-agent/1.0')
      return credentials
  else:
      print resp.status

def updateARecord(dns_service, zone_name, arecord, newvalue):
  args = {
    'project' : project,
    'managedZone' : zone_name
  }
  newset = {}
  response = dns_service.resourceRecordSets().list(**args).execute()
  # we assume that this is an additon only
  addition = {
    "kind": "dns#resourceRecordSet",
    "name": arecord,
    "rrdatas": [newvalue],
    "type": "A"
  }
  deletion = None
  # however if we find the record to exist we populate the deletion and match the addition
  for rrset in response['rrsets']:
    if (rrset['type'] == 'A') and (rrset['name'] == arecord):
      addition = dict(rrset)
      deletion = dict(rrset)
      addition['rrdatas'] = [newvalue]
  # override the TTL
  addition['ttl'] = 180
  body = { 
          'additions': [addition], 
          'deletions': [deletion]
         }
  args['body'] = body
  response = dns_service.changes().create(**args).execute()
#  print args
#  print 'Record set created, result object: '
#  print json.dumps(response,
#               sort_keys=True,
#               indent=4,
#               separators=(',', ': '))

if __name__ == '__main__':
    http = httplib2.Http()
    resp, project  = http.request(PROJECT_META, method='GET', body=None, headers={'Metadata-Flavor': 'Google'}) 
    credentials = service_auth()
    dns_service = build('dns', 'v1', http=credentials.authorize(http))
    resp, myip  = http.request(IP_META, method='GET', body=None, headers={'Metadata-Flavor': 'Google'}) 
    if resp.status == 200:
        if resp.status == 200:
            resp, myhostname  = http.request(HOST_META, method='GET', body=None, headers={'Metadata-Flavor': 'Google'}) 
            myhostname = myhostname.split('.c.')[0]
            updateARecord(dns_service, DNS_ZONE_NAME, '%s.%s.' % (myhostname, DNS_DOMAIN_NAME), myip)
        else:
            print resp.status
    else:
        print resp.status

以上是关于python 使用公共DNS区域中的主机名自动更新计算引擎实例IP的主要内容,如果未能解决你的问题,请参考以下文章

DNS相关

Python:如何使用特定的 DNS 服务器查找带有 IP 的主机名?

数据中心动态DNS+DHCP应用

部署DNS 服务---运维笔记

DNS

DNS 区域传送漏洞(dns-zone-tranfer)学习