最近要获取服务器各种参数,包括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. 在Ubuntu中安装Redis

    原文地址:http://blog.fens.me/linux-redis-install/ 在Ubuntu中安装Redis R利剑NoSQL系列文章,主要介绍通过R语言连接使用nosql数据库.涉及的 ...

  2. 《编写高质量代码——Web前端开发修炼之道》读后随笔

    结构样式行为的分离 结构标准包括XML标准.XHTML标准.HTML标准:样式标准有CSS标准:行为标准主要包括DOM标准和ECMAScript标准. 通常的项目会按照如上的方式进行分离,但自己曾今做 ...

  3. Uncle Sam 山姆大叔

    山姆大叔被用来代指“美国”或“美国政府”,主要在美国.英国,尤其是在新闻界中使用较多.“山姆大叔”是美国的绰号,它同自由女神一样,为世人所熟知. 形象 美国的报纸杂志.文学作品和漫画中,经常可以看到“ ...

  4. Vagrant网络配置

    Vagrant中网络配置 一.基本配置 Vagrant offers multiple options for how you are able to connect your guest machi ...

  5. SRM 391(1-250pt)

    DIV1 250pt 题意:给两个'a'-'z'的字符串,是否存在一个'a'-'z'的置换,使得能将一个字符串转化成另一个字符串. 解法:题意即是求,s1和s2对应位置出现的字符在原字符串中出现的次数 ...

  6. N - Tram - poj1847(简单最短路)

    题意:火车从一点开到另一点,轨道上有很多岔路口,每个路口都有好几个方向(火车能够选任意一个方向开),但是 默认的是 第一个指向的方向,所以如果要选择别的方向的话得 进行一次切换操作 ,给定一个起点一个 ...

  7. 什么是method swizzling

    其实跟字面的意思很相近.方法的调和.可以去修改oc中两个方法的调用. 这张图看起来会比较形象 20130718230430859.png 就是把两个实现调换具体的做法,首先,用Categroy建立自己 ...

  8. angularJS测试一 Karma Jasmine Mock

    AngularJS测试 一 测试工具 1.NodeJS领域:Jasmine做单元测试,Karma自动化完成单元测试,Grunt启动Karma统一项目管理,Yeoman最后封装成一个项目原型模板,npm ...

  9. mongoDb 给表添加+ 删除字段

    1 .添加一个字段.  url 代表表名 , 添加字段 content. 字符串类型. db.url.update({}, {$set: {content:""}}, {multi ...

  10. ASP.NET DropDownList1_SelectedIndexChanged使用

    DropDownList1.AutoPostBack 属性 今天写代码给DropDownList1添加DropDownList1_SelectedIndexChanged事件,在运行测试时发现Drop ...