Python 結合Ansible 把管理資產信息自動插入到CMDB中

資產管理對於任何公司來講都是件很是重要的事情,你們不用cmdb都有點很差意思出來見人了,上了CMDB以後基礎就是資產這塊,爲了避免苦逼似的一個個往裏邊錄入,因而用python 結合Ansible 寫了個自動收集資產信息,而後拿出本身須要關注的字段,自動insert 到cmdb 數據庫裏邊去。

咱們的cmdb 是開源改的,前端自定義好以後,後端的數據庫須要本身建立個表,建立表語句以下:
CREATE TABLE ansible_host (
id int(11) NOT NULL AUTO_INCREMENT,
hostname varchar(200) COLLATE utf8_bin DEFAULT NULL,
manufacturer varchar(200) COLLATE utf8_bin DEFAULT NULL,
os varchar(200) COLLATE utf8_bin DEFAULT NULL,
cpu_model varchar(200) COLLATE utf8_bin DEFAULT NULL,
cpu_count varchar(10) 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(200) COLLATE utf8_bin DEFAULT NULL,
ip varchar(255) COLLATE utf8_bin DEFAULT NULL,
mac_address varchar(255) COLLATE utf8_bin DEFAULT NULL,
sn varchar(20) COLLATE utf8_bin DEFAULT NULL,
PRIMARY KEY (id)
) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=utf8 COLLATE=utf8_bin;前端

python 代碼:
#gobal_fun 輔助模塊,時間和數據定義在這裏邊,正式程序直接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()python

主程序mysql

#!/usr/bin/env pythonsql

coding=utf-8

author :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(ass)
#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()後端

相關文章
相關標籤/搜索