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对html代码进行escape编码的方法
May 04 Python
解析Python中的生成器及其与迭代器的差异
Jun 20 Python
基于Python 装饰器装饰类中的方法实例
Apr 21 Python
基于anaconda下强大的conda命令介绍
Jun 11 Python
Python设计模式之工厂方法模式实例详解
Jan 18 Python
FFrpc python客户端lib使用解析
Aug 24 Python
python统计函数库scipy.stats的用法解析
Feb 25 Python
python GUI库图形界面开发之PyQt5表单布局控件QFormLayout详细使用方法与实例
Mar 06 Python
python shell命令行中import多层目录下的模块操作
Mar 09 Python
python如何建立全零数组
Jul 19 Python
python调用摄像头的示例代码
Sep 28 Python
弄清Pytorch显存的分配机制
Dec 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中的正规表达式(二)
2006/10/09 PHP
php有道翻译api调用方法实例
2014/12/22 PHP
Yii2框架视图(View)操作及Layout的使用方法分析
2019/05/27 PHP
php多进程应用场景实例详解
2019/07/22 PHP
javascript使用onclick事件改变选中行的颜色
2013/12/30 Javascript
JQuery实现动态添加删除评论的方法
2015/05/18 Javascript
JS利用cookie记忆当前位置的防刷新导航效果
2015/10/15 Javascript
Nodejs如何搭建Web服务器
2016/03/28 NodeJs
javascript表单处理具体实现代码(表单、链接、按钮)
2016/05/07 Javascript
JavaScript中数组常见操作技巧
2017/09/01 Javascript
详解ES6中的Map与Set集合
2019/03/22 Javascript
Layer.js实现表格溢出内容省略号显示,悬停显示全部的方法
2019/09/16 Javascript
jQuery操作事件完整实例分析
2020/01/10 jQuery
使用Vue Composition API写出清晰、可扩展的表单实现
2020/06/10 Javascript
Vue 3.0中jsx语法的使用
2020/11/13 Javascript
JavaScript中layim之整合右键菜单的示例代码
2021/02/06 Javascript
[54:53]2014 DOTA2国际邀请赛中国区预选赛 LGD-GAMING VS CIS 第二场
2014/05/23 DOTA
python 中文乱码问题深入分析
2011/03/13 Python
在Django框架中设置语言偏好的教程
2015/07/27 Python
解决python 输出是省略号的问题
2018/04/19 Python
深入浅析Python获取对象信息的函数type()、isinstance()、dir()
2018/09/17 Python
python隐藏终端执行cmd命令的方法
2019/06/24 Python
PyCharm2020.1.2社区版安装,配置及使用教程详解(Windows)
2020/08/07 Python
CSS3弹性盒模型开发笔记(二)
2016/04/26 HTML / CSS
详解移动端h5页面根据屏幕适配的四种方案
2020/04/15 HTML / CSS
美国围栏公司:Walpole Outdoors
2019/11/19 全球购物
波兰在线运动商店:YesSport
2020/07/23 全球购物
阿拉伯时尚购物网站:Nisnass
2021/02/07 全球购物
请问如下代码执行后a和b的值分别是什么
2016/05/05 面试题
竞选卫生委员演讲稿
2014/04/28 职场文书
公司放假通知怎么写
2015/04/15 职场文书
信仰观后感
2015/06/03 职场文书
SSM项目使用拦截器实现登录验证功能
2022/01/22 Java/Android
海弦WR-800F
2022/04/05 无线电
海康机器人重磅发布全新算法开发平台VM4.2
2022/04/21 数码科技
基于docker安装zabbix的详细教程
2022/06/05 Servers