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中的类,对象,方法,属性
Sep 11 Python
Python3单行定义多个变量或赋值方法
Jul 12 Python
win7+Python3.5下scrapy的安装方法
Jul 31 Python
python实现将文件夹下面的不是以py文件结尾的文件都过滤掉的方法
Oct 21 Python
Python的UTC时间转换讲解
Feb 26 Python
django 类视图的使用方法详解
Jul 24 Python
python实现图片压缩代码实例
Aug 12 Python
使用Python爬虫库requests发送请求、传递URL参数、定制headers
Jan 25 Python
python实现扫雷小游戏
Apr 24 Python
python 匿名函数与三元运算学习笔记
Oct 23 Python
用60行代码实现Python自动抢微信红包
Feb 04 Python
Python集合的基础操作
Nov 01 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边学边教》(02.Apache+PHP环境配置――上篇)
2006/12/13 PHP
使用PHP的日期与时间函数技巧
2008/04/24 PHP
PHP实现通用alert函数的方法
2015/03/11 PHP
php实现QQ空间获取当前用户的用户名并生成图片
2015/07/25 PHP
Laravel如何友好的修改.env配置文件详解
2017/06/07 PHP
Laravel用户授权系统的使用方法示例
2018/09/16 PHP
一个加密JavaScript的开源工具PACKER2.0.2
2006/11/04 Javascript
40个有创意的jQuery图片和内容滑动及弹出插件收藏集之二
2011/12/31 Javascript
为JS扩展Array.prototype.indexOf引发的问题探讨及解决
2013/04/24 Javascript
JS之Date对象和获取系统当前时间详解
2014/01/13 Javascript
禁止iframe脚本弹出的窗口覆盖了父窗口的方法
2014/09/06 Javascript
JavaScript 学习笔记之数据类型
2015/01/14 Javascript
45个JavaScript编程注意事项、技巧大全
2015/02/11 Javascript
chorme 浏览器记住密码后input黄色背景处理方法(两种)
2017/11/22 Javascript
Javascript中绑定click事件的四种方式介绍
2018/10/26 Javascript
vue+element树组件 实现树懒加载的过程详解
2019/10/21 Javascript
微信小程序后端(java)开发流程的详细步骤
2019/11/13 Javascript
node.JS事件机制与events事件模块的使用方法详解
2020/02/06 Javascript
解决vue中el-tab-pane切换的问题
2020/07/19 Javascript
Python实现二分查找与bisect模块详解
2017/01/13 Python
django-csrf使用和禁用方式
2020/03/13 Python
python字符串拼接+和join的区别详解
2020/12/03 Python
python爬虫利用代理池更换IP的方法步骤
2021/02/21 Python
英国领先的男装设计师服装独立零售商:Repertoire Fashion
2020/10/19 全球购物
客服工作职责
2013/12/11 职场文书
招聘专员岗位职责
2014/03/07 职场文书
协议书格式
2014/04/23 职场文书
个人贷款授权委托书样本
2014/10/07 职场文书
公司仓管员岗位职责
2015/04/01 职场文书
辩护词范文大全
2015/05/21 职场文书
2015年外贸业务员工作总结范文
2015/05/23 职场文书
工伤劳动仲裁代理词
2015/05/25 职场文书
浅谈什么是SpringBoot异常处理自动配置的原理
2021/06/21 Java/Android
MySQL中连接查询和子查询的问题
2021/09/04 MySQL
如何用vue实现网页截图你知道吗
2021/11/17 Vue.js
VUE解决跨域问题Access to XMLHttpRequest at
2022/05/06 Vue.js