python监控windows的CPU,

发布时间:2019-09-15 09:54:18编辑:auto阅读(1582)

    有一批windows系统需要监控,无论是zabbix、nagios都需要安装相关插件,操作起来比较麻烦。

    python的psutil模块可以跨平台监控linux、windows、mac等,于是使用python写监控脚本,然后利用py2exe工具将其打包成exe后,直接将其放到windows下直接运行即可。

    1.安装python2.7(32位)

    在https://www.python.org/downloads/ 下载适合系统的python

    安装后修改环境变量,“系统变量”----PATH最后添加“C:\Python27”

    2.安装psutil模块(32位)

    在https://pypi.python.org/pypi/psutil 下载适合系统的psutil

    在安装前需要先注册python2.7,否则会报错

    编辑注册脚本register.py

    #
    # script to register Python 2.0 or later for use with win32all
    # and other extensions that require Python registry settings
    #
    # written by Joakim Loew for Secret Labs AB / PythonWare
    #
    # source:
    # http://www.pythonware.com/products/works/articles/regpy20.htm
    #
    # modified by Valentine Gogichashvili as described in http://www.mail-archive.com/distutils-sig@python.org/msg10512.html
     
    import sys
     
    from _winreg import *
     
    # tweak as necessary
    version = sys.version[:3]
    installpath = sys.prefix
     
    regpath = "SOFTWARE\\Python\\Pythoncore\\%s\\" % (version)
    installkey = "InstallPath"
    pythonkey = "PythonPath"
    pythonpath = "%s;%s\\Lib\\;%s\\DLLs\\" % (
        installpath, installpath, installpath
    )
     
    def RegisterPy():
        try:
            reg = OpenKey(HKEY_CURRENT_USER, regpath)
        except EnvironmentError as e:
            try:
                reg = CreateKey(HKEY_CURRENT_USER, regpath)
                SetValue(reg, installkey, REG_SZ, installpath)
                SetValue(reg, pythonkey, REG_SZ, pythonpath)
                CloseKey(reg)
            except:
                print "*** Unable to register!"
                return
            print "--- Python", version, "is now registered!"
            return
        if (QueryValue(reg, installkey) == installpath and
            QueryValue(reg, pythonkey) == pythonpath):
            CloseKey(reg)
            print "=== Python", version, "is already registered!"
            return
        CloseKey(reg)
        print "*** Unable to register!"
        print "*** You probably have another Python installation!"
     
    if __name__ == "__main__":
        RegisterPy()
    启动dos,在register.py所在目录下运行python register.py。

    执行完成后,系统会提示“ Python 2.7 is already registered!”

    3.编写监控脚本(在此只监控CPU,内存,硬盘的使用率或空闲率,若有其他需要请自己完善)

    psutil相关使用文档请参考http://pythonhosted.org/psutil/

    #coding=utf8
    import psutil
    cpu = {'user' : 0, 'system' : 0, 'idle' : 0, 'percent' : 0}
    mem = {'total' : 0, 'avaiable' : 0, 'percent' : 0, 'used' : 0, 'free' : 0}
    
    #磁盘名称
    disk_id = []
    #将每个磁盘的total used free percent 分别存入到相应的list
    disk_total = []
    disk_used = []
    disk_free = []
    disk_percent = []
    
    #获取CPU信息
    def get_cpu_info():
    	cpu_times = psutil.cpu_times()
    	cpu['user'] = cpu_times.user
    	cpu['system'] = cpu_times.system
    	cpu['idle']	= cpu_times.idle
    	cpu['percent'] = psutil.cpu_percent(interval=2)
    #获取内存信息
    def get_mem_info():
    	mem_info = psutil.virtual_memory()
    	mem['total'] = mem_info.total
    	mem['available'] = mem_info.available
    	mem['percent'] = mem_info.percent
    	mem['used'] = mem_info.used
    	mem['free'] = mem_info.free
    #获取磁盘
    def get_disk_info():
    	for id in psutil.disk_partitions():
    		if 'cdrom' in id.opts or id.fstype == '':
    			continue
    		disk_name = id.device.split(':')
    		s = disk_name[0]
    		disk_id.append(s)
    		disk_info = psutil.disk_usage(id.device)
    		disk_total.append(disk_info.total)
    		disk_used.append(disk_info.used)
    		disk_free.append(disk_info.free)
    		disk_percent.append(disk_info.percent)
    		
    
    if __name__ == '__main__':
    	get_cpu_info()
    	cpu_status = cpu['percent']
    	print u"CPU使用率: %s %%" % cpu_status
    	get_mem_info()
    	mem_status = mem['percent']
    	print u"内存使用率: %s %%" % mem_status
    	get_disk_info()
    	for i in range(len(disk_id)):
    		print u'%s盘空闲率: %s %%' % (disk_id[i],100 - disk_percent[i])
    	raw_input("Enter enter key to exit...")  

    执行结果如下:


    4.打包python脚本

    要想监控脚本在其他windows上运行需要安装python环境,但我们可以将监控脚本打包成exe程序发布,只要运行exe程序就能够执行,如何实现呢?

    (1)安装打包程序py2exe-0.6.9.win32-py2.7.exe

    在http://sourceforge.net/projects/py2exe/files/py2exe/0.6.9/ 下载相应的版本

    下载后直接安装即可

    (2)编写一个简单的编译脚本setup_py2exe.py

    from distutils.core import setup
    import py2exe
    
    setup(console=["monitor.py"])
    (3)打包

    进入dos,在setup_py2exe.py所在的目录运行python setup_py2exe.py py2exe

    运行后会在当前目录生成两个文件夹:build和disk,build里面的是一些中间文件可以不用理会,dist里面会产生monitor.exe及其他文件,monitor.exe就是我们需要运行的exe程序,我们需要将dist文件夹发布。

    注意:当我们将dist文件夹发布到其他windows机器后,直接运行monitor.exe后,有可能会报错“由于应用程序配置不正确,应用程序未能启动”。这是由于py2exe打包的程序需要9.0.21022.8这个版本的MSVCR90.DLL,我们可以从网上下载并将其放到dist目录下一起发布。另除了9.0.21022.8这个版本的MSVCR90.DLL外,我们还需要Microsoft.VC90.CRT.manifest文件放在dist目录。

    Microsoft.VC90.CRT.manifest如下:

    <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
          <assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
          <noInheritable></noInheritable>
          <assemblyIdentity type="win32" name="Microsoft.VC90.CRT" version="9.0.21022.8" processorArchitecture="x86" publicKeyToken="1fc8b3b9a1e18e3b"></assemblyIdentity>
          <file name="msvcr90.dll" />
          </assembly>
    ok,我们再次将dist目录发布到其他windows服务器上,运行monitor.exe程序即可。




关键字