抓取服务器硬件信息脚本

说明:
本例hard.py文件是抓取本地配置的脚本,然后往数据库写,写之前会做判断是否有该和数据,如果没有才会插入,如果没有不会插入数据
本例用的python版本是3.5,用的库有os,sys,time,psutil,pymysql。
脚本内容如下:

#!/usr/local/python3/bin/python3
import psutil,os,sys,pymysql,time
#cpu型号
cpu_model = os.popen('cat /proc/cpuinfo | grep name | cut -f2 -d: | uniq -c|cut -c 10-50').read()
cpu_count = psutil.cpu_count()
cpu_core = psutil.cpu_count(logical=False)
#内存相关
info = psutil.virtual_memory()
#总内存(M)
total_memory = int(info.total/1024/1024/1024)
#用了多少内存(M)
use_memory = int(info.used/1024/1024)
#空闲内存(M)
free_memory = int(info.free/1024/1024)
#磁盘容量
D_result = 0
Disk_size = os.popen("fdisk -l|grep Disk|grep -v identifier|awk '{print $3}'|sed 's/,//g'").read()
with open('/tmp/a.txt','w') as f:
     f.write(Disk_size)
with open('/tmp/a.txt','r') as f1:
     for line in f1:
         line = line.strip('\n')
         D_result = D_result + float(line)
#IP地址
out = os.popen("ifconfig | grep 'inet addr:' | grep -v '127.0.0.1' | cut -d: -f2 | awk '{print $1}' | head -1").read()
ip = out.split('\n')[0]
print('''
机器配置如下:
cpu型号: %s
cpu逻辑数量: %s
cpu物理核心数: %s
内存(G): %s
磁盘容量(G): %s
IP地址: %s
'''%(cpu_model,cpu_count,cpu_core,total_memory,D_result,ip))
#插入库
db= pymysql.connect(host="192.168.1.14",user="abc",password="abc",db="cmdb",port=3306)
cur = db.cursor()
check_ip_sql = "select ip from cmdb_host where ip='%s'"%ip
cur.execute(check_ip_sql)
result = cur.fetchone()
db.commit()
#判断插入的数据是否存在,如果存在不插入,反之则插入数据
if result == None:
     print("开始添加记录.......")
     time.sleep(1)
     sql_insert = "insert into cmdb_host(cpu,mem,disk,ip) values('%s','%sG','%sG','%s');" %(cpu_count,total_memory,D_result,ip)
     try:
       cur.execute(sql_insert)
       #提交
       db.commit()
       print("添加成功!^_^")
     except Exception as e:
       #错误回滚
       db.rollback() 
     finally:
       db.close()
elif ip == result[0]:
     print("此条记录已添加过")
     pass

猜你喜欢

转载自blog.51cto.com/461884/2141246