最近要获取服务器各种参数,包括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执行shell获取硬件参数写入mysql的更多相关文章

  1. 利用python执行shell脚本 并动态传参 及subprocess基本使用

    最近工作需求中 有遇到这个情况  在web端获取配置文件内容 及 往shell 脚本中动态传入参数 执行shell脚本这个有多种方法   最后还是选择了subprocess这个python标准库 su ...

  2. python 执行shell命令

    1.os模块中的os.system()这个函数来执行shell命令 1 2 3 >>> os.system('ls') anaconda-ks.cfg  install.log  i ...

  3. HTTP协议与使用Python获取数据并写入MySQL

    一.Http协议 二.Https协议 三.使用Python获取数据 (1)urlib (2)GET请求 (3)POST请求 四.爬取豆瓣电影实战 1.思路 (1)在浏览器中输入https://movi ...

  4. python 使用getopt 获取配置参数

    在工程中特别是稍微大一点的项目基本上都会用到配置,就会涉及到配置文件的读取,配置参数的读取. 常用的解析配置文件的是configParser,解析命令行参数的则为getopt. getopt的参数可以 ...

  5. python和shell获取命令行参数的区别

    一.命令行参数的取得对于一些功能性的脚本来说非常有用,不至于将功能写死在脚本中. shell的命令行参数直接用 $ 1,$2 等就可以直接获取 其中 $1 表示 第二个参数,即命令行的第一个参数,因为 ...

  6. python执行shell命令

    1 os.system 可以返回运行shell命令状态,同时会在终端输出运行结果 例如 ipython中运行如下命令,返回运行状态status os.system('cat /etc/passwdqc ...

  7. python执行shell实时输出

    1.使用readline可以实现 import subprocess def run_shell(shell): cmd = subprocess.Popen(shell, stdin=subproc ...

  8. Linux记录-shell获取hdfs表查询mysql

    #!/bin/sh hdfs dfs -ls /user/hive/warehouse | awk '{print $8}' | awk -F "/" '{print $5}' & ...

  9. python 执行shell

    一.import os ex: 1.os.system('ls') ----并不能得到返回值 2.output = os.popen('ls') res = output.read() ----能得到 ...

随机推荐

  1. 什么是Socket,为什么要用Socket

    应用层通过传输层进行数据通信时,TCP和UDP会遇到同时为多个应用程序进程提供并发服务的问题.多个TCP连接或多个应用程序进程可能需要通过同一个TCP协议端口传输数据.为了区别不同的应用程序进程和连接 ...

  2. HTML embed标签使用方法和属性详解

    一.基本语法   代码如下:   embed src=url   说明:embed可以用来插入各种多媒体,格式可以是 Midi.Wav.AIFF.AU.MP3等等,Netscape及新版的IE 都支持 ...

  3. Java内存管理以及各个内存区域详解

    一.概述 原文链接:http://blog.csdn.net/l271640625/article/details/39761439 Java虚拟机在执行Java程序的过程中会把它所管理的内存划分为若 ...

  4. npm常用命令总结

    p.p1 { margin: 0.0px 0.0px 0.0px 0.0px; font: 11.0px Menlo; color: #000000; background-color: rgba(2 ...

  5. Stage3D_Game_Programming:渲染3D模型

    OBJ是文件,先来解释下OBJ文件.随便找一个OBJ文件,用文本查看: ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 # ...

  6. ie8下$(document).on('mouseover mouseout','ul li',function(){})的bug

    $(document).on('mouseover mouseout','ul li',function(){ if (event.type == 'mouseover') {           c ...

  7. Hadoop与HBase中遇到的问题

    1. Hadoop中遇到的问题 曾经所遇到的问题因为没有记录,所以忘了 (1)NameNode没有启动成功, 是因为你对HDFS多次格式化,导致datanode中与namenode中的VERSION文 ...

  8. Android ExpandableListView实例Demo

    前几篇文章介绍了Listview.但在实际开发中也常常会用到多层的Listview来展示数据,比方qq中的好友展示,所以这张来了解一下ExpandableListview.基本思想与Listview大 ...

  9. Java读书笔记二(封装类)

    1.介绍 都知道java中基本数据类型有非常多,比方string,int--,可是基本数据类型与对象之间是不同的.但非常多情况下,我们希望将基本数据类型当作对象使用,这时候就须要用到封装类. 2.封装 ...

  10. POJ3169 Layout(差分约束系统)

    POJ3169 Layout 题意: n头牛编号为1到n,按照编号的顺序排成一列,每两头牛的之间的距离 >= 0.这些牛的距离存在着一些约束关系:1.有ml组(u, v, w)的约束关系,表示牛 ...