国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

python執行shell獲取硬件參數寫入mysql的方法

2020-02-23 06:18:02
字體:
來源:轉載
供稿:網友

本文實例講述了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)

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 长武县| 台北市| 奉化市| 怀柔区| 华宁县| 临颍县| 嘉荫县| 垫江县| 讷河市| 思茅市| 中卫市| 固安县| 若羌县| 铁岭县| 曲松县| 广德县| 东海县| 若羌县| 安康市| 饶阳县| 柘荣县| 菏泽市| 鲁山县| 岑巩县| 奉化市| 自治县| 诸城市| 名山县| 武汉市| 绥阳县| 博白县| 东兰县| 卓资县| 中卫市| 余江县| 明水县| 南皮县| 凤城市| 景洪市| 三江| 甘南县|