博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
抓取服务器硬件信息脚本
阅读量:6893 次
发布时间:2019-06-27

本文共 1844 字,大约阅读时间需要 6 分钟。

说明:

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

#!/usr/local/python3/bin/python3import 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 = 0Disk_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型号: %scpu逻辑数量: %scpu物理核心数: %s内存(G): %s磁盘容量(G): %sIP地址: %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'"%ipcur.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

转载于:https://blog.51cto.com/461884/2141246

你可能感兴趣的文章
"安全删除硬件并弹出媒体"的列表中出现内置硬盘的解决办法.
查看>>
LINUX中JDK环境变量配置
查看>>
linux 切换用户之后变成-bash-3.2$的解决方法
查看>>
我的友情链接
查看>>
使用list
查看>>
Ubuntu 12.04 安装 gcc-4.8 及 gdb 7.6
查看>>
DOM设置表格隔行变色js代码及鼠标悬停在哪行,哪行字体就加粗效果
查看>>
GII 和 DEBUG 模块出现 403 解决
查看>>
shell历史命令记录功能
查看>>
kali linux软件源
查看>>
centos6设置静态IP
查看>>
cocos2d_x在windows环境下的方向键支持
查看>>
Mysql数据库恢复,Ibdata1文件删除数据恢复成功
查看>>
Maven学习总结(11)——Maven Tomcat7自动部署
查看>>
Shell 中常用的sqlplus 代码段
查看>>
Maven学习总结(1)——Maven入门
查看>>
Linux java环境配置
查看>>
mysql ====查询命令介绍(5)
查看>>
Ffmpeg,mencoder视频格式转换
查看>>
【经验收集】完全卸载SQLServer 2008 R2的步骤
查看>>