0%

Python脚本抓取腾讯云上主机名称及对应IP

一、背景

  • 现在要求通过api接口,把腾讯云上所有的主机实例名称和对应内网ip地址抓取下来保存到dnsmasq文件中,供内部解析使用
  • 公司内部有自己搭建的DNSMasq集群,用来解析主机名及对应IP。因为几千台机器,管理时大家都是通过主机名来区别什么服务,前提是每台主机命名要符合规范

二、脚本

2.1 python脚本

  • Vim /root/python/GetDNS.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#! /usr/bin/env python3
# -*- coding: utf-8 -*-

import os
from tencentcloud.common import credential
from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException
from tencentcloud.cvm.v20170312 import cvm_client, models

#HOST_FILE="/etc/dnsmasq.hosts"
#if os.path.exists(HOST_FILE):
# pass
#else:
# print("没有发现DNS FILE,将会创建!")
# os.system("touch /etc/dnsmasq.hosts")
def get_exist():
exist_ip = []
if not os.path.exists('/etc/dnsmasq.hosts'):
return exist_ip
with open('/etc/dnsmasq.hosts', 'r') as f:
for data in f.readlines():
exist_ip.append(data.strip().split(' ')[0])
return exist_ip


def add_data():
secretId = 'AxxxxxxxxxxxxxxxxA'
secretKey = 'keyxxxxxxxxxxxxxxxxxxxxKEY' //此处填写腾讯云账户里面的ID及对应的KEY
cred = credential.Credential(secretId=secretId, secretKey=secretKey)
client = cvm_client.CvmClient(cred, "ap-shanghai")
req = models.DescribeInstancesRequest()
resp = client.DescribeInstances(req)
exist_ip = get_exist()
for i in range(int(resp.TotalCount / 20) + 1):
req.Offset = i * 20
resp = client.DescribeInstances(req)
for j in resp.InstanceSet:
if j.PrivateIpAddresses[0] in exist_ip:
continue
line = '{} {}.ad.tuhu.cn'.format(j.PrivateIpAddresses[0], j.InstanceName)
#line = '{} {}'.format(j.PrivateIpAddresses[0], j.InstanceName)
with open('/etc/dnsmasq.hosts', 'a+') as f:
f.write(line + '\n')


if __name__ == '__main__':
add_data()

2.2 定时任务

  • 本脚本每一分钟会去云上抓取一次解析记录,保存的记录是增量的,发现腾讯云上新建机器,则会把新纪录保存到本地hosts文件中,如果云上机器名称变更掉,则本地会有两条记录(同一个ip会对应两个主机名,解决方法可以清空本地解析记录,让脚本自动重新跑一次)
1
*/1  * * * * echo `date`>>/var/log/dnsmasq/getlist.log && python /root/python/GetDNS.py  >>/var/log/dnsmasq/getlist.log
坚持原创技术分享,您的支持将鼓励我继续创作!
-------------本文结束感谢您的阅读-------------