资产管理对于任何公司来说都是件非常重要的事情,大家不用cmdb都有点不好意思出来见人了,上了CMDB之后基础就是资产这块,为了不苦逼似的一个个往里边录入,于是用python 结合Ansible 写了个自动收集资产信息,然后拿出自己需要关注的字段,自动insert 到cmdb 数据库里边去。
Our CMDB is open source, and after the front-end customization, the back-end database needs to create the table itself, creating a table statement as follows:
CREATE TABLEansible_host
(
id
Int (one) not NULL auto_increment,
hostname
varchar (COLLATE) Utf8_bin DEFAULT NULL,
manufacturer
varchar (COLLATE) Utf8_bin DEFAULT NULL,
os
varchar (COLLATE) Utf8_bin DEFAULT NULL,
cpu_model
varchar (COLLATE) Utf8_bin DEFAULT NULL,
cpu_count
varchar (COLLATE) Utf8_bin DEFAULT NULL,
cpu_core
varchar (255) COLLATE Utf8_bin DEFAULT NULL,
memory_totally
varchar (255) COLLATE Utf8_bin DEFAULT NULL,
swap_totally
varchar (255) COLLATE Utf8_bin DEFAULT NULL,
disk
varchar (COLLATE) Utf8_bin DEFAULT NULL,
ip
varchar (255) COLLATE Utf8_bin DEFAULT NULL,
mac_address
varchar (255) COLLATE Utf8_bin DEFAULT NULL,
sn
varchar (COLLATE) Utf8_bin DEFAULT NULL,
PRIMARY KEY (id
)
) Engine=innodb auto_increment=0 DEFAULT Charset=utf8 collate=utf8_bin;
Python code:
#gobal_fun Auxiliary module, time and data defined here side, formal program direct import
#!/usr/bin/env python
Import datetime
Import time
Import Sys
Import MySQLdb as MySQL
D1=datetime.datetime.now ()
#input =open (sys.argv[1], ' R ')
D2= (D1-datetime.timedelta (Days=1)). Strftime ('%y-%m-%d ')
D3= (D1-datetime.timedelta (Days=1)). Strftime ('%d/%b/%y ')
Day = Time.strftime ("%Y")
#outpu =open (d2+ ' __hourpv.csv ', ' A + ')
#outip =open (' ip' +d2+ '. csv ', ' A + ')
Dk=time.strftime ("%d/%b/%y", Time.localtime ()) + ': 00 '
Da=time.strftime ("%d/%b/%y", Time.localtime ())
conn= Mysql.connect (user= "root", passwd= "Vivame", db= "Falcon", charset= "UTF8")
cur = conn.cursor ()
Main program
#!/usr/bin/env python
Coding=utf-8author:wosun
Gro=raw_input ("Pls input ansible group:")
Import Ansible.runner as Arun
Import Gobal_fun
Def get_info ():
Ass_list=[]
Runner = Arun. Runner (
Module_name= ' Setup ',
Module_args= ',
Pattern= '%s '%gro,
forks=10
)
Results=runner.run ()
Info=results[' contacted ']
For Host,val in Info.items ():
For i in val[' ansible_facts ' ["AnsibleDevices"]:
If I[0:2] not in ("SR"):
Dis=str (i+ '+val[' ansible_facts ' [' ansible_devices '][i][' size '])
Ass=host,str (val[' ansible_facts '] ["ansible_product_name"]), str (val[' ansible_facts ' ["ansibleDistribution"] ) + "" +st)
Ass_list.append (The)
#for I in Ass_list:
Print I
Msql= "INSERT into (,,,,,, ansible_host
hostname
manufacturer
os
cpu_model
cpu_count
cpu_core
memory_totally
, ' swa")
Try
Gobal_fun.cur.executemany (Msql,ass_list)
Gobal_fun.conn.commit ()
Gobal_fun.cur.close ()
Gobal_fun.conn.close ()
Print "Success Insert"
Except Exceptioin,e:
Conn.rollback ()
Print E
If name = = "main":
Get_info ()
Python combines ansible to automatically insert management asset information into the CMDB