蓝鲸--CMDB批量修改主机属性值
1. 通过导入excel,批量更新主机属性值
2. 日志模块,输出到屏幕、文件。
version: 1
formatters:
error:
format: '%(asctime)s - %(name)s - %(levelname)s - %(processName)s - %(filename)s - %(message)s'
datefmt: "%Y-%m-%d %H:%M:%S"
info:
format: '%(asctime)s - %(levelname)s - %(filename)s - %(message)s'
datefmt: "%Y-%m-%d %H:%M:%S"
handlers:
console:
class: logging.StreamHandler
level: DEBUG
formatter: info
stream: ext://sys.stdout
file:
class: logging.handlers.RotatingFileHandler
level: DEBUG
formatter: info
backupCount: 3
filename: logconfig
maxBytes: 1024
encoding: utf-8
mode: a
console_err:
class: logging.StreamHandler
level: ERROR
formatter: error
stream: ext://sys.stderr
loggers:
bk_log:
level: DEBUG
handlers: [console,file]
propagate: yes
root:
level: DEBUG
handlers: [console_err]
- bk_app_code、bk_app_secret值获取
开发者中心-->应用中心-->S-mart应用--->任选一个如:bk_itsm-->基本信息-->应用ID、应用TOKEN即为:bk_app_code、bk_app_secret
其中配置中心、作业平台属于原子应用,无该信息。取任意一个即可。
import requests
import json
import xlrd
import logging
import logging.config
import yaml
"""
使用规则:
1. 更新的的行数不能超过500
2. xls的sheet页、文件名请勿更改
3. 第二列的字段名,应根据blueking中导出的字段名来定。并且有不可修改项,以及部分枚举内容,不可自定义修改。
"""
class BkHostUpdate(object):
def __init__(self):
self.host = 'http://paas.bktencent.com'
self.addr = '/api/c/compapi/v2/cc/batch_update_host/'
self.url = self.host + self.addr
self.headers = {"Accept":"application/json"}
def update_host(self, params):
try:
response = requests.post(self.url, data=json.dumps(params), headers=self.headers)
logger.debug(response.json())
except Exception as err:
logger.error(err)
class ReadExcel(object):
def __init__(self):
self.params = {
"bk_app_code": "bk_nodeman",
"bk_app_secret": "xx",
"bk_username": "admin",
}
self.update_list = []
def output_params(self):
try:
data = xlrd.open_workbook(r'tce_bk.xls')
table = data.sheet_by_name('bk_host')
nrows = table.nrows # 获取有效行数
ncols = table.ncols # 获取有效列数
title_value = table.row_values(1, start_colx=0, end_colx=None)
if ncols < 500: # 每次修改的列数不能超过500
for row in range(2, nrows):
row_value = table.row_values(row, start_colx=0, end_colx=None)
param_tmp = {}
properties = {}
for i in range(1, len(title_value)):
if not row_value[i]:
continue
else:
properties[title_value[i]] = row_value[i]
param_tmp['properties'] = properties
param_tmp['bk_host_id'] = int(row_value[0])
logger.info(param_tmp)
self.update_list.append(param_tmp)
self.params['update'] = self.update_list
return self.params
else:
logger.error('修改的行数超过500')
except Exception as err:
logger.error(err)
if __name__ == "__main__":
with open('logging.yaml', 'r') as log_conf:
dict_conf = yaml.load(log_conf, Loader=yaml.FullLoader)
logging.config.dictConfig(dict_conf)
logger = logging.getLogger('bk_log')
excel = ReadExcel()
params = excel.output_params()
# print(params)
conn = BkHostUpdate()
conn.update_host(params)