linux-node0.oldboyedu.com 192.168.1.30 安装salt-master,salt-minion
linux-node1.oldboyedu.com 192.168.1.31 安装salt-minion
这里主要用到saltstack的grains,就是saltstack minion端生成的一些静态信息,比如CPU,内存,主机名什么的,而这些就是我们所需要的
执行salt \* grains.items,会打印一大堆的默认抓取的信息,其中一部分,如下
我们当然只挑我们需要的,操作如下
获取主机名
salt linux-node1.oldboyedu.com grains.item host
获取IP地址
salt linux-node1.oldboyedu.com grains.item ipv4
获取CPU核数
salt \* grains.item num_cpus
以此类推,根据自己所需,提取~~~
值得注意的是,grains信息里面并没有硬盘信息,所以还需通过disk.usage这个选项,得到我们所需的硬盘信息
执行salt linux-node1.oldboyedu.com disk.usage
其中1K-blocks即我们所需的硬盘信息,根据需求只需要盘/,所以后面就会计算这个盘的配额
11.py代码:
import salt.client as sc
import json
###salt调用
local = sc.LocalClient()
###目标主机指定
tgt = "*"
###获取grains,disk信息
grains = local.cmd(tgt,"grains.items")
diskusage = local.cmd(tgt,"disk.usage")
###主要应用列表即文件开头
app_name = ["tomcat","zookeeper","redis","mysql","nginx"]
cols = "Hostname,IP address,RAM(GB),CPU num,Operation,DATA /(GB),project"
###打开一个.csv文件,以便写入
ret_file = open("ret.csv","w")
###首先写入开头,有点字段名的意思
ret_file.write(cols + "\n")
try:
for i in grains.keys():
###打印信息可注释掉
print grains[i]["nodename"]
print "ipv4" + ":" ,grains[i]["ipv4"]
print "mem_total" + ":" , grains[i]["mem_total"] / 1024 + 1
print "num_cpus" + ":" , grains[i]["num_cpus"]
print "osfullname" + ":" , grains[i]["osfullname"]
print "release" + ":" , grains[i]["lsb_distrib_id"]
###万一主机没有/ 数据盘1048576是1024x102
if "/" not in diskusage[i]:
print "diskusage" + ":" + "have no /data disk"
else:
data_vol = int(diskusage[i]["/"]["1K-blocks"])
print "diskusage" + ":" , data_vol / 1048576
###去掉127.0.0.1这个地址
ipv4 = str(grains[i]["ipv4"]).replace(", '127.0.0.1'","")
###因为一些历史遗留问题,这里取得不是主机名,而是salt-minion的id名,用以判断主要应用
hostname = grains[i]["id"]
ipv4 = str(grains[i]["ipv4"]).replace(", '127.0.0.1'","")
ipv4 = ipv4.replace(",","and")
mem = grains[i]["mem_total"] / 1024 + 1
num_cpu = grains[i]["num_cpus"]
OS = grains[i]["osfullname"] + grains[i]["lsb_distrib_id"]
if "/" not in diskusage[i]:
disk_data = "None"
else:
disk_data = data_vol / 1048576
###通过minion ID名来判断主要运行服务,比如xx-mysql-1,则运行mysql
for j in app_name:
if j in hostname.lower():
app = j
break
else:
app = "undefined"
c = ","
###连接并写入
line = hostname + c + ipv4 + c + str(mem) + c + str(num_cpu) + c + str(OS) + c + str(disk_data) + c + app
ret_file.write(line + "\n")
except Exception,e:
print "Exception:\n",e
finally:
ret_file.close()
执行salt \* grains.items,发现"lsb_distrib_id"代替了原来的"lsb_distrib_release",所以上面用了"lsb_distrib_id"
[root@linux-node0 ~]# python 11.py
linux-node0
ipv4: ['127.0.0.1', '192.168.1.30', '192.168.1.38']
mem_total: 1
num_cpus: 1
osfullname: CentOS Linux
release: CentOS Linux
diskusage: 16
linux-node1
ipv4: ['127.0.0.1', '192.168.1.31', '192.168.122.1']
mem_total: 3
num_cpus: 1
osfullname: CentOS Linux
release: CentOS Linux
diskusage: 16
执行后在同一目录下生成ret.csv文件,打开如下:
通过Python利用saltstack进行生成服务器资产清单
原文地址:http://blog.51cto.com/2290153/2113198