最近要获取服务器各种参数,包括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. Java实现人民币大写代码解析

    想要实现人民币大写,在发票等场景中使用?? 1234.56显示为:壹仟贰佰叁拾肆元伍角陆分,那就往下看看吧! 本程序可以实现 0 到 9999 9999 9999.994 以内的人民币大写转换,精确到 ...

  2. 由浅入深吃透MVC框架,驯服烂代码

    MVC 已经成为客户端的主流编程框架,相信客户端工程师对它并不陌生,甚至在开发过程中,不通过思考都会自动使用 MVC 框架编程.但在工作过程中,发现许多小伙伴也只是使用 MVC,对于为什么这样使用并不 ...

  3. Java接口,抽象类

    1.接口(interface),接口被用来建立类与类之间关联的标准. 2.抽象类(abstract class),只要类中有一个抽象方法,此类就被标记为抽象类.实际上抽象类除了被继承之外没有任何意义. ...

  4. Redis sort命令

    http://www.cnblogs.com/linjiqin/archive/2013/06/14/3135921.html 1.添加 投票选项到 redis的  List 和HashMap lis ...

  5. Servlet跳转

    方便自己查询,嫌低级的勿喷.... 在Servlet中跳转有两种: 1.客户端跳转 在Servlet中要进行客户端跳转(地址栏的地址信息将发生改变),直接使用HttpServletResponse接口 ...

  6. iOS 开发 入门:使用Ad Hoc 进行用户测试

    在完成iOS开发,准备进行发布之前,我们都希望App能在周围的朋友之间先进行测 试,提提意见,修改完善之后再发布到App Store上.Apple考虑到这一点,因此通过Ad Hoc来实现发布前的用户测 ...

  7. Windows下Postgre SQL数据库通过Slony-I 实现数据库双机同步备份

    一. 我们要实现的环境是windows xp.windows2003上安装Postgre SQL数据库,实现目的是两台数据库服务器进行数据库同步,即数据库同步更新.删除.插入等对数据库的操作. 二. ...

  8. 使用easy_install安装numpy、pandas、matplotlib及各种第三方模块

    倒腾了一晚上最终把题目中的环境配好了.以下简要说明.留作资料.并共享. 1.安装python. 在cmd中能进入python环境,通过把python路径加入到系统路径中就可以实现. 2.安装easy- ...

  9. android开发launcher

    1. launcher是桌面应用程序 一. android.intent.category.LAUNCHER与android.intent.category.HOME的差别?      android ...

  10. “too many open files" ----增大打开的文件数

     http://www.cnblogs.com/ibook360/archive/2012/05/11/2495405.html [root@localhost ~]# ab -n -c http:/ ...