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的Tkinter实现一个简易计算器
Dec 31 Python
Python画图学习入门教程
Jul 01 Python
Python3调用微信企业号API发送文本消息代码示例
Nov 10 Python
使用python实现链表操作
Jan 26 Python
python样条插值的实现代码
Dec 17 Python
django的ORM模型的实现原理
Mar 04 Python
anaconda中更改python版本的方法步骤
Jul 14 Python
执行Django数据迁移时报 1091错误及解决方法
Oct 14 Python
Python制作简易版小工具之计算天数的实现思路
Feb 13 Python
Python图像处理库PIL的ImageEnhance模块使用介绍
Feb 26 Python
python 的numpy库中的mean()函数用法介绍
Mar 03 Python
Python图像处理二值化方法实例汇总
Jul 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
一个PHP操作Access类(PHP+ODBC+Access)
2007/01/02 PHP
jQuery EasyUI API 中文文档 - DateBox日期框
2011/10/15 PHP
smarty缓存用法分析
2014/12/16 PHP
php中让人头疼的浮点数运算分析
2016/10/10 PHP
常用PHP封装分页工具类
2017/01/14 PHP
PHP+Redis 消息队列 实现高并发下注册人数统计的实例
2018/01/29 PHP
Yii框架 session 数据库存储操作方法示例
2019/11/18 PHP
Div自动滚动到末尾的代码
2008/10/26 Javascript
window.name代替cookie的实现代码
2010/11/28 Javascript
理解JavaScript中的对象 推荐
2011/01/09 Javascript
JS 操作Array数组的方法及属性实例解析
2014/01/08 Javascript
解决angular的post请求后SpringMVC后台接收不到参数值问题的方法
2015/12/10 Javascript
jQuery绑定事件-多种实现方式总结
2016/05/09 Javascript
javascript滚轮控制模拟滚动条
2016/10/19 Javascript
微信开发 js实现tabs选项卡效果
2016/10/28 Javascript
JS经典正则表达式笔试题汇总
2016/12/15 Javascript
select下拉框插件jquery.editable-select详解
2017/01/22 Javascript
JavaScript实现动态增删表格的方法
2017/03/09 Javascript
js实现下拉框效果(select)
2017/03/28 Javascript
Bootstrap Table 在指定列中添加下拉框控件并获取所选值
2017/07/31 Javascript
JavaScript实现多个物体同时运动
2020/03/12 Javascript
Python中的引用和拷贝浅析
2014/11/22 Python
Python读取Json字典写入Excel表格的方法
2018/01/03 Python
Python3.5装饰器原理及应用实例详解
2019/04/30 Python
Python3将数据保存为txt文件的方法
2019/09/12 Python
python 追踪except信息方式
2020/04/25 Python
python 进程池pool使用详解
2020/10/15 Python
以下为Windows NT 下的32 位C++程序,请计算sizeof 的值
2016/12/07 面试题
RIP版本1跟版本2的区别
2013/12/30 面试题
sort命令的作用和用法
2013/08/25 面试题
年级组长自我鉴定
2014/02/22 职场文书
安全生产管理责任书
2014/04/16 职场文书
2014副镇长民主生活会个人对照检查材料思想汇报
2014/09/30 职场文书
个人委托函范文
2015/01/29 职场文书
学雷锋献爱心活动总结
2015/05/11 职场文书
2015秋季田径运动会广播稿
2015/08/19 职场文书