通过Python使用saltstack收集服务器资产信息自动入库

由于各种因素导致公司服务器资产信息不完善,想要重新整理一份资产信息表,借鉴《通过Python使用saltstack生成服务器资产清单》的脚本稍微修改,完善自己想要的资产信息,并写入数据库!在此做个记录,以便后期资产更新。


脚本内容如下:

[python]  view plain  copy
  1. # coding=utf-8  
  2. import salt.client as sc  
  3. import MySQLdb  
  4.   
  5. db = MySQLdb.connect("192.168.62.200""root""kbsonlong""test")  
  6. cur = db.cursor()  
  7. #cur.execute('truncate table hostinfo')   #清空主机信息表,当主机较多时慎重处理  
  8.   
  9. ###salt调用  
  10. local = sc.LocalClient()  
  11. ###目标主机指定  
  12. tgt = "*"  
  13.   
  14. ###获取grains,disk信息  
  15. grains = local.cmd(tgt, "grains.items")  
  16. diskusage = local.cmd(tgt, "disk.usage")  
  17.   
  18. cols = "主机,IP,内存(GB),CPU型号,CPU核数,操作系统 ,/容量(GB),/(使用率),/data容量(GB),/data(使用率),/data1容量(GB),/data1(使用率),网卡mac,是否虚拟主机"  
  19.   
  20. ###打开一个.csv文件,以便写入  
  21. ret_file = open("hostinfo.csv""w")  
  22. ###首先写入开头,有点字段名的意思  
  23. ret_file.write(cols + "\n")  
  24. try:  
  25.     for i in grains.keys():  
  26.         ###去掉127.0.0.1这个地址  
  27.         hostname = grains[i]["nodename"]  
  28.         ipv4 = str(grains[i]["ipv4"]).replace("'127.0.0.1',", "")  
  29.         ipv4 = ipv4.replace(",""|")  
  30.         mem = grains[i]["mem_total"] / 1024 + 1  
  31.         num_cpu = grains[i]["num_cpus"]  
  32.         OS = grains[i]["os"] + ' ' + grains[i]["osrelease"]  
  33.         cpu = grains[i]["cpu_model"]  
  34.         virtual = grains[i]["virtual"]  
  35.   
  36.         ##磁盘容量  
  37.         if "/" not in diskusage[i]:  
  38.             disk_used = " "  
  39.             disk_capacity = " "  
  40.         else:  
  41.             disk_used = float(diskusage[i]["/"]["1K-blocks"])/1048576  
  42.             disk_capacity = diskusage[i]["/"]["capacity"]  
  43.         if "/data" not in diskusage[i]:  
  44.             disk_data_used = " "  
  45.             disk_data_capacity = " "  
  46.         else:  
  47.             disk_data_used = float(diskusage[i]["/data"]["1K-blocks"])/1048576  
  48.             disk_data_capacity = diskusage[i]["/data"]["capacity"]  
  49.   
  50.         if "/data1" not in diskusage[i]:  
  51.             disk_data1_used = " "  
  52.             disk_data1_capacity = " "  
  53.         else:  
  54.             disk_data1_used = float(diskusage[i]["/data"]["1K-blocks"])/1048576  
  55.             disk_data1_capacity = diskusage[i]["/data"]["capacity"]  
  56.   
  57.   
  58.         ####获取网卡mac信息  
  59.         # if "eth0" not in grains[i]["hwaddr_interfaces"]:  
  60.         #     eth0=" "  
  61.         # else:  
  62.         #     eth0=grains[i]["hwaddr_interfaces"]["eth0"]  
  63.         #  
  64.         # if "eth1" not in grains[i]["hwaddr_interfaces"]:  
  65.         #     eth1=" "  
  66.         # else:  
  67.         #     eth1=grains[i]["hwaddr_interfaces"]["eth1"]  
  68.         grains[i]["hwaddr_interfaces"].pop("lo")  
  69.         interfaces=str(grains[i]["hwaddr_interfaces"]).replace(","" |")  
  70.   
  71.   
  72.         cur.execute('select hostname from hostinfo')  ###获取资产列表中的主机名  
  73.         L = []  
  74.         for host in cur.fetchall():  
  75.             L.append(host[0]);  
  76.         hostnames = ''.join(L)  
  77.         if hostname in hostnames:                  ##判断主机是否已经入库,如果存在输出提示,不存在则入库  
  78.             T = [( str(ipv4), int(mem), str(cpu), int(num_cpu), str(OS), str(virtual),str(hostname))]  
  79.             sql = "update  hostinfo set IP=%s, Mem=%s ,CPU=%s, CPUs=%s, OS=%s ,virtual=%s where hostname=%s"  
  80.             cur.executemany(sql, T)  
  81.             print "%s 已经在资产列表!" % hostname  
  82.         else:  
  83.             T = [(str(hostname), str(ipv4), int(mem), str(cpu), int(num_cpu), str(OS), str(virtual))]  
  84.             sql = "insert into hostinfo (hostname,IP,Mem,CPU,CPUs,OS,virtual) values (%s, %s ,%s, %s, %s ,%s, %s)"  
  85.             cur.executemany(sql, T)  
  86.         ###连接并写入  
  87.         c = ","  
  88.         line = hostname + c + ipv4 + c + str(mem) + c + str(cpu) + c + str(num_cpu) + c + str(OS) + c + str(  
  89.             disk_used) + c + str(disk_capacity) + c + str(  
  90.             disk_data_used) + c + str(disk_data_capacity) + c + str(disk_data1_used) + c + str(  
  91.             disk_data1_capacity)  + c  + interfaces + c + str(virtual)  
  92.         ret_file.write(line + "\n")  
  93. except Exception, e:  
  94.     print "Exception:\n", e  
  95. finally:  
  96.     ret_file.close()  
  97.     cur.close()  
  98.     db.close()  






Mysql表结构

[sql]  view plain  copy
  1. /*  
  2. Navicat MySQL Data Transfer  
  3.   
  4. Source Server         : oms  
  5. Source Server Version : 50173  
  6. Source Host           : 192.168.62.200:3306  
  7. Source Database       : test  
  8.   
  9. Target Server Type    : MYSQL  
  10. Target Server Version : 50173  
  11. File Encoding         : 65001  
  12.   
  13. Date: 2016-10-28 15:07:45  
  14. */  
  15.   
  16. SET FOREIGN_KEY_CHECKS=0;  
  17.   
  18. -- ----------------------------  
  19. -- Table structure for hostinfo  
  20. -- ----------------------------  
  21. DROP TABLE IF EXISTS `hostinfo`;  
  22. CREATE TABLE `hostinfo` (  
  23.   `id` int(11) NOT NULL AUTO_INCREMENT,  
  24.   `hostname` varchar(255) NOT NULL,  
  25.   `IP` varchar(255) DEFAULT NULL,  
  26.   `Mem` int(100) DEFAULT NULL,  
  27.   `CPU` varchar(255) DEFAULT NULL,  
  28.   `CPUS` int(100) DEFAULT NULL,  
  29.   `OS` varchar(255) DEFAULT NULL,  
  30.   `virtual` varchar(255) DEFAULT NULL,  
  31.   PRIMARY KEY (`id`)  
  32. ) ENGINE=MyISAM AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;  
来源:http://youerning.blog.51cto.com/10513771/1746075

猜你喜欢

转载自blog.csdn.net/llq_200/article/details/79259223
今日推荐