python执行shell获取硬件参数写入mysql的方法


Posted in Python onDecember 29, 2014

本文实例讲述了python执行shell获取硬件参数写入mysql的方法。分享给大家供大家参考。具体分析如下:

最近要获取服务器各种参数,包括cpu、内存、磁盘、型号等信息。试用了Hyperic HQ、Nagios和Snmp,它们功能都挺强大的,但是于需求不是太符,亦或者太heavy。

于是乎想到用python执行shell获取这些信息,python执行shell脚本有以下三种方法:

1. os.system()

os.system('ls')

#返回结果0或者1,不能得到命令的输出

2. os.popen()
output = os.popen('ls')

print output.read()

#打印出的是命令输出,但是得不到执行的返回值

3. commands.getstatusoutput()
(status, output) = commands.getstatusoutput('ls')

print status, output

#打印出返回值和命令输出

可以根据需要选取其中一种方法,以下是python执行shell获取硬件参数写入mysql,并定期更新的程序:
'''

Created on Dec 10, 2014
@author: liufei

'''

#coding=utf-8

import time, sched, os, string

from datetime import datetime

import MySQLdb

 

s = sched.scheduler(time.time,time.sleep)
def event_func():

    try:

        #主机名

        name = os.popen(""" hostname """).read()

        #cpu数目

        cpu_num = os.popen(""" cat /proc/cpuinfo | grep processor | wc -l """).read()

        #内存大小

        mem = os.popen(""" free | grep Mem | awk '{print $2}' """).read()

        #机器品牌

        brand = os.popen(""" dmidecode | grep 'Vendor' | head -1 | awk -F: '{print $2}' """).read()

        #型号

        model = os.popen(""" dmidecode | grep 'Product Name' | head -1 | awk -F: '{print $2}' """).read()

        #磁盘大小

        storage = os.popen(""" fdisk -l | grep 'Disk /dev/sd' | awk 'BEGIN{sum=0}{sum=sum+$3}END{print sum}' """).read()

        #mac地址

        mac = os.popen(""" ifconfig -a | grep HWaddr | head -1 | awk '{print $5}' """).read()

        

        name = name.replace("\n","").lstrip()

        cpu_num =  cpu_num.replace("\n","").lstrip()

        memory_gb = round(string.atof(mem.replace("\n","").lstrip())/1000.0/1000.0, 1)

        brand = brand.replace("\n","").lstrip()

        model = model.replace("\n","").lstrip()

        storage_gb = storage.replace("\n","").lstrip()

        mac = mac.replace("\n","").lstrip()

        

        print name

        print cpu_num

        print memory_gb

        print storage_gb

        print brand

        print model

        print mac

    

        conn=MySQLdb.connect(host='xx.xx.xx.xx',user='USERNAME',passwd='PASSWORD',db='DBNAME',port=3306)

        cur=conn.cursor()

        cur.execute('select mac from servers where mac=%s',mac)

        data = cur.fetchone()
        if data is None:

            value = [name, brand, model, memory_gb, storage_gb, cpu_num, mac, datetime.now(), datetime.now()]

            cur.execute("insert into servers(name, brand, model, memory_gb, storage_gb, cpu_num, mac,  created_at, updated_at) values(%s, %s, %s, %s, %s, %s, %s, %s, %s)",value)            

        else:

            value1 = [name, brand, model, memory_gb, storage_gb, cpu_num, datetime.now(), mac]

            cur.execute("update servers set name=%s,brand=%s,model=%s,memory_gb=%s,storage_gb=%s,cpu_num=%s, updated_at=%s where mac=%s",value1)

           

        conn.commit()

        cur.close()

        conn.close()

        

    except MySQLdb.Error,e:

        print "Mysql Error %d: %s" % (e.args[0], e.args[1])

    

def perform(inc):

    s.enter(inc,0,perform,(inc,))

    event_func()

    

def mymain(inc=10):

    s.enter(0,0,perform,(inc,))

    s.run()

 

if __name__ == "__main__":

    mymain()

希望本文所述对大家的Python程序设计有所帮助。

Python 相关文章推荐
Python字符串处理函数简明总结
Apr 13 Python
python实现web方式logview的方法
Aug 10 Python
requests和lxml实现爬虫的方法
Jun 11 Python
python读文件保存到字典,修改字典并写入新文件的实例
Apr 23 Python
Python考拉兹猜想输出序列代码实践
Jul 05 Python
pandas 对日期类型数据的处理方法详解
Aug 08 Python
Python 70行代码实现简单算式计算器解析
Aug 30 Python
tensorflow 实现从checkpoint中获取graph信息
Feb 10 Python
详解python常用命令行选项与环境变量
Feb 20 Python
python logging模块的使用
Sep 07 Python
如何用用Python将地址标记在地图上
Feb 07 Python
Python面向对象之成员相关知识总结
Jun 24 Python
简单的抓取淘宝图片的Python爬虫
Dec 25 #Python
简单使用Python自动生成文章
Dec 25 #Python
Python 抓取动态网页内容方案详解
Dec 25 #Python
利用Psyco提升Python运行速度
Dec 24 #Python
Python解决鸡兔同笼问题的方法
Dec 20 #Python
Python列表计数及插入实例
Dec 17 #Python
Python二维码生成库qrcode安装和使用示例
Dec 16 #Python
You might like
关于时间计算的结总
2006/12/06 PHP
PHP类的静态(static)方法和静态(static)变量使用介绍
2012/02/19 PHP
PHP实现生成透明背景的PNG缩略图函数分享
2014/07/08 PHP
PHP使用redis实现统计缓存mysql压力的方法
2015/11/14 PHP
thinkphp实现图片上传功能
2016/01/13 PHP
Yii2-GridView 中让关联字段带搜索和排序功能示例
2017/01/21 PHP
JQuery 学习技巧总结
2010/05/21 Javascript
JavaScript Memoization 让函数也有记忆功能
2011/10/27 Javascript
图片在浏览器中底部对齐 解决方法之一
2011/11/30 Javascript
JS中eval函数的使用示例
2013/07/21 Javascript
DEDECMS如何为文章添加HOT NEW标志图片
2015/08/14 Javascript
jQuery实现的网页左侧在线客服效果代码
2015/10/23 Javascript
jQuery zclip插件实现跨浏览器复制功能
2015/11/02 Javascript
JS实现星星评分功能实例代码(两种方法)
2016/06/09 Javascript
js实现固定宽高滑动轮播图效果
2017/01/13 Javascript
vue项目中,main.js,App.vue,index.html的调用方法
2018/09/20 Javascript
python 算法 排序实现快速排序
2012/06/05 Python
Python中字典(dict)和列表(list)的排序方法实例
2014/06/16 Python
python生成随机mac地址的方法
2015/03/16 Python
举例区分Python中的浅复制与深复制
2015/07/02 Python
Python基本语法经典教程
2016/03/11 Python
python实现多线程的两种方式
2016/05/22 Python
python实现一个简单的并查集的示例代码
2018/03/19 Python
python实现多层感知器
2019/01/18 Python
Python实现Word表格转成Excel表格的示例代码
2020/04/16 Python
英国领先的奢侈品零售商之一:CRUISE
2016/12/02 全球购物
英国文胸专家:AmpleBosom.com
2018/02/06 全球购物
Linux管理员面试题 Linux admin interview questions
2014/11/01 面试题
优秀应届本科生求职信
2014/07/19 职场文书
民主评议党员自我评价材料
2014/09/18 职场文书
三严三实心得体会范文
2014/10/13 职场文书
团队拓展训练心得体会
2016/01/12 职场文书
Mac M1安装mnmp (Mac+Nginx+MySQL+PHP) 开发环境
2021/03/29 PHP
nginx如何将http访问的网站改成https访问
2021/03/31 Servers
css常用字体属性与背景属性介绍
2022/02/28 HTML / CSS
在ubuntu下安装go开发环境的全过程
2022/08/05 Golang