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编写简单的定时器的方法
May 02 Python
Python实现大文件排序的方法
Jul 10 Python
使用py2exe在Windows下将Python程序转为exe文件
Mar 04 Python
Python基于回溯法子集树模板解决马踏棋盘问题示例
Sep 11 Python
Python3使用PyQt5制作简单的画板/手写板实例
Oct 19 Python
python kmeans聚类简单介绍和实现代码
Feb 23 Python
解决pandas无法在pycharm中使用plot()方法显示图像的问题
May 24 Python
在Pandas中DataFrame数据合并,连接(concat,merge,join)的实例
Jan 29 Python
python替换字符串中的子串图文步骤
Jun 19 Python
django 类视图的使用方法详解
Jul 24 Python
Tkinter中复选菜单是否被选中的判断与设置方式
Mar 04 Python
python 获取域名到期时间的方法步骤
Feb 10 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文章内容分页并生成相应的htm静态页面代码
2010/06/07 PHP
PHP gbk环境下json_dencode传送来的汉字
2012/11/13 PHP
PHP 观察者模式的实现代码
2013/05/10 PHP
PHP实现PDO的mysql数据库操作类
2014/12/12 PHP
Prototype使用指南之selector.js说明
2008/10/26 Javascript
一个页面元素appendchild追加到另一个页面元素的问题
2013/01/27 Javascript
js解析xml字符串和xml文档实现原理及代码(针对ie与火狐)
2013/02/02 Javascript
js螺旋动画效果的具体实例
2013/11/15 Javascript
全面解析DOM操作和jQuery实现选项移动操作代码分享
2016/06/07 Javascript
JS数组去掉重复数据只保留一条的实现代码
2016/08/11 Javascript
vue利用better-scroll实现轮播图与页面滚动详解
2017/10/20 Javascript
Vue单页面应用保证F5强刷不清空数据的解决方案
2018/01/31 Javascript
angular4自定义表单控件[(ngModel)]的实现
2018/11/23 Javascript
vue拖拽排序插件vuedraggable使用方法详解
2020/08/21 Javascript
Vue入门之数量加减运算操作示例
2018/12/11 Javascript
Jquery实现无缝向上循环滚动列表的特效
2019/02/13 jQuery
详解如何在vue项目中使用layui框架及采坑
2019/05/05 Javascript
echarts大屏字体自适应的方法步骤
2019/07/12 Javascript
vue.js中ref和$refs的使用及示例讲解
2019/08/14 Javascript
Element Carousel 走马灯的具体实现
2020/07/26 Javascript
[00:36]DOTA2上海特级锦标赛 LGD战队宣传片
2016/03/04 DOTA
Python MD5文件生成码
2009/01/12 Python
基于python批量处理dat文件及科学计算方法详解
2018/05/08 Python
Python中filter与lambda的结合使用详解
2019/12/24 Python
Python面向对象封装操作案例详解 II
2020/01/02 Python
使用CSS3制作倾斜导航条和毛玻璃效果
2017/09/12 HTML / CSS
美国饼干礼物和美食甜点购买网站:Cheryl’s
2020/05/28 全球购物
学生宿舍管理制度
2014/01/30 职场文书
《老王》教学反思
2014/02/23 职场文书
工作作风整顿个人剖析材料
2014/10/11 职场文书
好媳妇事迹材料
2014/12/24 职场文书
三下乡个人总结
2015/03/04 职场文书
2016秋季幼儿园开学寄语
2015/12/03 职场文书
2016年小学“我们的节日·中秋节”活动总结
2016/04/05 职场文书
golang import自定义包方式
2021/04/29 Golang
python办公自动化之excel的操作
2021/05/23 Python