config\conf.yaml
#API Token:ODgyNjY2NDk1NzE2Oif97iBMfBu+3NnSlhKiUm9W5g8f
#参考资料
#https://confluence.atlassian.com/insightapps/insight-apps-1085180635.html
#https://insight-javadoc.riada.io/insight-javadoc-8.6/insight-rest/
#https://developer.atlassian.com/cloud/insight/rest/api-group-icon/
#本地服务器API URL +具体路径
#http://10.251.21.16:8080/rest/insight/1.0/
base_Info:
    #访问的基础信息
    Url: 'http://10.251.21.16:8080/rest/insight/1.0/'
    Token: 'Bearer ODgyNjY2NDk1NzE2Oif97iBMfBu+3NnSlhKiUm9W5g8f'
    Insight_info:
        证书: [  'Name','有效期']
        网络端口: ['Name', 'Type']
        IP地址: [ 'Name','归属服务器', '归属服务分类']
        业务范围: ['Name', '描述', '环境']
        账号(人员): ['Name',  'Type', '所有者']
        运维团队: ['Name', '运维主岗', '运维备岗']
        服务器: [ 'Name', '服务器类型', '操作系统', '服务分类']
        服务域名: [ 'Name', '服务名称', 'IP地址', '证书']
        Operating System: [ 'Manufacturer', 'OS Architecture', 'Version', 'Build Number', 'Kernel', 'ServicePack Major Version', 'ServicePack Minor Version', 'Object Hash']
        员工: [ 'Name','EmployeeNumber']
        OS: ['Key', 'Name', 'Created', 'Updated']
        环境: ['Name', '描述']
        服务端口: [ 'Name','端口', '服务分类']
        服务管理: [ 'Name','描述', '许可证', '运维团队', '技术支持团队', '服务状态', '业务范围']
        License: [ 'License Key', 'Host', 'Application', 'Operating System', 'End Date', 'Object Hash']
        服务分类: [ 'Name','服务名称', '服务分类名称']
        服务依赖: [ 'Name','远程IP地址', '远程端口', '服务账号', '描述', '服务名称']
        printer: [ '打印机名称']
        账号(服务): ['Name',]
        服务商公司名称: [ 'Name',  '产品', '销售', '售前', '售后']
        IP地址分类: [ 'Name', ]
        职位(服务商): ['Name',]
        支持人员(供应商): [ 'Name', '邮箱', '手机', '所属公司', '职位']
        备份: [ 'Name','备份类型', '备份时间', '备份频率']
        服务器类型: [ 'Name',]
get_All_AttributeInfo.py
#说明:完成,用于返回所获取的字典样式
#返回值类型  字典
#例一
#in:get_all_attributeInfo('ByAttribute')
#out:{'证书': {320: '有效期'}, '网络端口': {273: 'Type'},
#例二
#in:get_all_attributeInfo()
#out:{'证书': { '有效期':'320'}, '网络端口': {'Type':'273' },
#例三
#in:objType_type_ByID
#out:{'证书': {320: 'label'}, '网络端口': {273: 'label'},

import requests,yaml,os,json,time


config_path = os.path.join(os.getcwd(), 'config\conf.yaml')
with open(config_path,'rb') as f:
   conf = f.read()
c_info=yaml.load(conf) 

Token=c_info["base_Info"]["Token"]
Init_Url=c_info["base_Info"]["Url"]
headers = {
   "Accept": "application/json",
   "Content-Type": "application/json",
   "Authorization": Token
   }

objType_Attributes_ByID={}
objType_Attributes_ByAttribute={}
objType_type_ByID={}


#查询所有对象模式,每次去一个对象,有多少页就取多少次
# objectschema/list
url=Init_Url+r"iql/objects?page={0}&resultPerPage=1"
test_Res = requests.request( "GET", url.format(0), headers=headers)
total_page=json.loads(test_Res.text)["pageSize"]

def get_all_attributeInfo(  ):
	for i in range(total_page):
		Res= json.loads(requests.request( "GET", url.format(i+1), headers=headers).text)
		objType_Name=Res['objectEntries'][0]["objectType"]['name']
		objType_ID=Res['objectEntries'][0]["objectType"]['id']
		Name_ID=str(objType_Name)+'_ID'
		if objType_Name not in objType_Attributes_ByID.keys():
			objType_Attributes_ByID[objType_Name]={}
			objType_Attributes_ByID[objType_Name][objType_ID]='ID'
			objType_Attributes_ByAttribute[objType_Name]={}
			objType_Attributes_ByAttribute[objType_Name]['ID']=objType_ID
			# objType_Attributes_ByAttribute[objType_Name][Name_ID.upper()] =objType_ID #便于根据用户名反查用户ID信息
			objType_type_ByID[objType_Name]={}

	   #objType_Attribute 是一个字典,里面存放有关某一字段的关键信息
		for objType_Attribute in Res['objectTypeAttributes']:

			# print(objType_Attribute)
		  #通过c_info["base_Info"]['Insight_info'] 判断对象分类是否存在,如果是存在,增将分类加入分类列表
			if objType_Attribute['name'] in c_info["base_Info"]['Insight_info'][objType_Name]:
				if objType_Attribute['id'] not in objType_Attributes_ByID[objType_Name].keys():
					objType_Attributes_ByID[objType_Name][objType_Attribute['id']]=objType_Attribute['name']
					objType_Attributes_ByAttribute[objType_Name][objType_Attribute['name']]=objType_Attribute['id']
					if objType_Attribute['type'] ==0:
						objType_type_ByID[objType_Name][objType_Attribute['id']]='label'
					elif objType_Attribute['type'] ==1:
						objType_type_ByID[objType_Name][objType_Attribute['id']]='obj'
					elif objType_Attribute['type'] ==7:
						objType_type_ByID[objType_Name][objType_Attribute['id']]='status'
					else:
						objType_type_ByID[objType_Name][objType_Attribute['id']]='unknown'


	return(objType_Attributes_ByID,objType_Attributes_ByAttribute,objType_type_ByID)


if __name__ == '__main__':
	info =get_all_attributeInfo()[2]
	print(info)


jira_createObjects.py
#说明:
#状态:
#返回值类型:
#例一
#in:  1、对象分类 ID,2、对象属性字典[{"objectTypeAttributeId":value},]
#out:
import requests,yaml,os,json
config_path = os.path.join(os.getcwd(), 'config\conf.yaml')
with open(config_path,'rb') as f:
   conf = f.read()
c_info=yaml.load(conf) 
from get_All_AttributeInfo import get_all_attributeInfo
from get_objects_All import get_object_list

Token=c_info["base_Info"]["Token"]
Init_Url=c_info["base_Info"]["Url"]
headers = {
   "Accept": "application/json",
   "Content-Type": "application/json",
   "Authorization": Token
   }

url=Init_Url+"object/create"

#获取对象分类的属性,并以字典的形式存在,形如 {categoryName:{categoryID:ID, categoryTypeDesc:descID}}


objType_Attributes_ByID,objType_Attributes_ByAttribute,objType_type_ByID=get_all_attributeInfo()
object_dick=get_object_list()

def createObjects(info):
	#判断计划创建的对象,在insight 内是否存在
	for obj_s in object_dick.values():
		if info['Name'].upper()==obj_s['Name'].upper():
			print('对象{0}:{1}已经存在,停止创建'.format(info['category'],info['Name']))
			break
	else:

		objectTypeId=	objType_Attributes_ByAttribute[info['category']]['ID']
		attributes=[]
		# print(objectTypeId)

		for Attribute_keys in objType_Attributes_ByAttribute[info['category']].keys():
			attribute={}
			attribute["objectAttributeValues"]={}
			# attribute["objectAttributeValues"].append({})





			if Attribute_keys not in ['ID', 'Key',  'Created', 'Updated', ] and  not Attribute_keys.endswith('_ID'):

				if info[Attribute_keys]:
					attribute["objectTypeAttributeId"]=objType_Attributes_ByAttribute[info['category']][Attribute_keys]


					if objType_type_ByID[ info['category']][attribute["objectTypeAttributeId"]]=='obj':
						Name_ID=(info[Attribute_keys]).upper()
						print(Name_ID)
						# print(objType_Attributes_ByAttribute.items())
						for item in object_dick.keys():

							if Name_ID == object_dick[item]['Name'].upper():
								attribute["objectAttributeValues"]=[{'value':object_dick[item]['ID']}]
							else:
								continue
					else:	
						attribute["objectAttributeValues"]=[{'value':info[Attribute_keys]}]
					print(attribute)
				attributes.append(attribute.copy())
			print(attributes)

		payload = json.dumps( {
					"objectTypeId": objectTypeId,
					"attributes":attributes,

							} )


		response = requests.request("POST",url,data=payload,headers=headers)


		print(json.loads(response.text))

if __name__ == '__main__':
	info={'category':'账号(人员)','Name':'e05531','Type':'办公','所有者':'hans han'}
	createObjects(info)


get_fileList.py
#说明:获取脚本所在目录下data 文件夹及其子文件夹内容,并以字典的形式返回
#状态:完成
#返回值类型:
#例一
#in:  文件所在目录
#out:{'Q:\\专项工作\\3、资产整理\\02、数据处理脚本\\data\\e05522': ['01、固定资产表.xlsx', '02、硬件资产.xlsx', '03、软件资产.xlsx',
import os
file_dir=os.getcwd()
file_dic={}
def getFlist(file_dir):
    for root, dirs, file_list in os.walk(file_dir):
        if len(file_list)>0:
            file_dic[root]=file_list
    return file_dic

if __name__ == '__main__':

    resDir = os.getcwd()+'\data'
    files = getFlist(resDir)

    print(files)
read_excel.py
#说明:获取Excel 文件内容,并返回   同时返回文件名
#状态:完成
#返回值类型:pandas data frame  
#例一
#in:  Excel 文件所在路径
#out: dataframe 类型数据


# 判断是否为浮点数
def isNum2(value):
	try:
		x=float(value)
		return (True)
	except Exception as e:
		return(False)


import pandas as pd
def get_content(WorkBook,WorkSheet):
	data=pd.read_excel(WorkBook, sheet_name =WorkSheet)
	# print(data.head())
	return data

get_objects_All
#说明:获取jira Insight 内所有的对象及其关键属性, 关键属性名称维护再conf 文件内Insight_info 内
#状态:完成,
#返回值类型:字典
#例一
#in:无
#out:{31: {'Name': 'Prd_AnyShare6_All', 'ID': 31, 'CategoryName': 'License', 'CategoryID': 11, 'End Date': '2022-02-22'}}

import requests,yaml,os,json,time
from get_All_AttributeInfo import get_all_attributeInfo

config_path = os.path.join(os.getcwd(), 'config\conf.yaml')
with open(config_path,'rb') as f:
   conf = f.read()
c_info=yaml.load(conf) 

Token=c_info["base_Info"]["Token"]
Init_Url=c_info["base_Info"]["Url"]
headers = {
   "Accept": "application/json",
   "Content-Type": "application/json",
   "Authorization": Token
   }

All_AttributeInfo=get_all_attributeInfo()[0]

#查询所有对象模式,每次去一个对象,有多少页就取多少次
# objectschema/list
url=Init_Url+r"iql/objects?page={0}&resultPerPage=1"
test_Res = requests.request( "GET", url.format(0), headers=headers)
total_page=json.loads(test_Res.text)["pageSize"]

#用于查询数据,展现显示为参数:值
def get_object_list():
	obj_list=[]
	obj_info={}
	for  i in range(total_page):

		Res= json.loads(requests.request( "GET", url.format(i+1), headers=headers).text)
		
		obj_info[Res['objectEntries'][0]['id']]={}
		obj_info[Res['objectEntries'][0]['id']]['Name']=Res['objectEntries'][0]["label"]   #{id:{'Name':name, }}
		obj_info[Res['objectEntries'][0]['id']]['ID']=Res['objectEntries'][0]['id']
		obj_info[Res['objectEntries'][0]['id']]['CategoryName']=Res['objectEntries'][0]["objectType"]['name']
		obj_info[Res['objectEntries'][0]['id']]['CategoryID']=Res['objectEntries'][0]["objectType"]['id']

		objType_Name=Res['objectEntries'][0]["objectType"]['name']


		for item_attributesInfo in Res['objectEntries'][0]["attributes"]:
			if item_attributesInfo['objectTypeAttributeId'] in All_AttributeInfo[objType_Name].keys():
				try:
					# print(All_AttributeInfo[objType_Name][item_attributesInfo['objectTypeAttributeId']]+':'+item_attributesInfo['objectAttributeValues'][0]['value'])
					obj_info[Res['objectEntries'][0]['id']][All_AttributeInfo[objType_Name][item_attributesInfo['objectTypeAttributeId']]]=item_attributesInfo['objectAttributeValues'][0]['value']
				except Exception as e:
					try:
						# print(All_AttributeInfo[objType_Name][item_attributesInfo['objectTypeAttributeId']]+':'+item_attributesInfo['objectAttributeValues'][0]['referencedObject']['label'])
						obj_info[Res['objectEntries'][0]['id']][All_AttributeInfo[objType_Name][item_attributesInfo['objectTypeAttributeId']]]=item_attributesInfo['objectAttributeValues'][0]['referencedObject']['label']
					except Exception as d:
						# print(All_AttributeInfo[objType_Name][item_attributesInfo['objectTypeAttributeId']]+':'+item_attributesInfo['objectAttributeValues'][0]['displayValue'])
						obj_info[Res['objectEntries'][0]['id']][All_AttributeInfo[objType_Name][item_attributesInfo['objectTypeAttributeId']]]=item_attributesInfo['objectAttributeValues'][0]['displayValue']

						# time.sleep(30)
					# print(e)

	return(obj_info)
  


if __name__ == '__main__':
	All_obj=get_object_list()
	print(All_obj)


get_typeAttributes.py
#获取各个分类的属性信息 , 可用于更新conf 文件中 Insight_info
import requests,yaml,os,json,time


config_path = os.path.join(os.getcwd(), 'config\conf.yaml')
with open(config_path,'rb') as f:
   conf = f.read()
c_info=yaml.load(conf) 

Token=c_info["base_Info"]["Token"]
Init_Url=c_info["base_Info"]["Url"]
headers = {
   "Accept": "application/json",
   "Content-Type": "application/json",
   "Authorization": Token
   }


obj_typeAttributes={}

#查询所有对象模式,每次去一个对象,有多少页就取多少次
# objectschema/list
url=Init_Url+r"iql/objects?page={0}&resultPerPage=1"
test_Res = requests.request( "GET", url.format(0), headers=headers)
total_page=json.loads(test_Res.text)["pageSize"]


for  i in range(total_page):
   Res= json.loads(requests.request( "GET", url.format(i+1), headers=headers).text)
   obj_typeName=Res['objectEntries'][0]["objectType"]['name']
   if obj_typeName not in obj_typeAttributes.keys():
      obj_typeAttributes[obj_typeName]={}

   for objectTypeAttribute in Res['objectTypeAttributes']:
      # if objectTypeAttribute['name'] in c_info["base_Info"]['Insight_info'][obj_typeName]:

      obj_typeAttributes[obj_typeName][objectTypeAttribute['id']]=objectTypeAttribute['name']

for top_key in obj_typeAttributes.keys():
   print(top_key +': '+ str(obj_typeAttributes[top_key].values()))
posted on 2021-12-23 12:49  vmsky  阅读(261)  评论(0编辑  收藏  举报