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 相关文章推荐
c++生成dll使用python调用dll的方法
Jan 20 Python
Python数组条件过滤filter函数使用示例
Jul 22 Python
深入了解Python数据类型之列表
Jun 24 Python
python numpy 部分排序 寻找最大的前几个数的方法
Jun 27 Python
如何利用python给图片添加半透明水印
Sep 06 Python
Python 网络编程之TCP客户端/服务端功能示例【基于socket套接字】
Oct 12 Python
python mysql 字段与关键字冲突的解决方式
Mar 02 Python
python和php哪个容易学
Jun 19 Python
django 模型字段设置默认值代码
Jul 15 Python
Python列表嵌套常见坑点及解决方案
Sep 30 Python
appium+python自动化配置(adk、jdk、node.js)
Nov 17 Python
python中count函数知识点浅析
Dec 17 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 会话(session 时间设定)使用入门代码
2008/06/05 PHP
php计算2个日期的差值函数分享
2015/02/02 PHP
修改WordPress中文章编辑器的样式的方法详解
2015/12/15 PHP
Yii中表单用法实例详解
2016/01/05 PHP
php大小写转换函数(strtolower、strtoupper)用法介绍
2017/11/17 PHP
PHP date()格式MySQL中插入datetime方法
2019/01/29 PHP
告诉大家什么是JSON
2008/06/10 Javascript
fireworks菜单生成器mm_menu.js在 IE 7.0 显示问题的解决方法
2009/10/20 Javascript
js setTimeout()函数介绍及应用以倒计时为例
2013/12/12 Javascript
Java/JS获取flash高宽的具体方法
2013/12/27 Javascript
jquery $("#variable") 循环改变variable的值示例
2014/02/23 Javascript
js实现Select下拉框具有输入功能的方法
2015/02/06 Javascript
javascript基础知识
2016/06/07 Javascript
Javascript随机标签云代码实例
2016/06/21 Javascript
JS导出PDF插件的方法(支持中文、图片使用路径)
2016/07/12 Javascript
基于angularjs实现图片放大镜效果
2016/08/31 Javascript
AngularJS 获取ng-repeat动态生成的ng-model值实例详解
2016/11/29 Javascript
angular实现form验证实例代码
2017/01/17 Javascript
利用Vue v-model实现一个自定义的表单组件
2017/04/27 Javascript
jQuery菜单实例(全选,反选,取消)
2017/08/28 jQuery
使用 Node.js 模拟滑动拼图验证码操作的示例代码
2017/11/02 Javascript
webpack多入口多出口的实现方法
2018/08/17 Javascript
Element-ui 自带的两种远程搜索(模糊查询)用法讲解
2021/01/29 Javascript
Python生成随机MAC地址
2015/03/10 Python
详解Python程序与服务器连接的WSGI接口
2015/04/29 Python
Python实现程序的单一实例用法分析
2015/06/03 Python
Python实现脚本锁功能(同时只能执行一个脚本)
2017/05/10 Python
Python3实现发送QQ邮件功能(html)
2017/12/15 Python
pycharm中使用anaconda部署python环境的方法步骤
2018/12/19 Python
python修改txt文件中的某一项方法
2018/12/29 Python
Python数据处理篇之Sympy系列(五)---解方程
2019/10/12 Python
css 如何让背景图片拉伸填充避免重复显示
2013/07/11 HTML / CSS
员工三分钟演讲稿
2014/08/19 职场文书
golang操作redis的客户端包有多个比如redigo、go-redis
2022/04/14 Golang
一篇文章带你掌握SQLite3基本用法
2022/06/14 数据库
纯CSS打字动画的实现示例
2022/08/05 HTML / CSS