Python执行PowerShell命令和wmic命令获取CPU、内存和硬盘信息,实现Windows主机监控功能

Python执行PowerShell命令和wmic命令获取CPU、内存和硬盘信息,实现Windows主机监控功能

#!/usr/bin/env python
# encoding: utf-8

## Windows监控脚本
## Python3

## 2022年09月14日
## 开始编写
## 参考1:https://blog.csdn.net/weixin_42133116/article/details/114371614
## 参考2:https://blog.csdn.net/sherlocklcy/article/details/124529094

import os
import re
import sys
import time
import datetime
import argparse
from glob import glob
import subprocess as sp

class PowerShell:
    def __init__(self, coding, ):
        cmd = [self._where('PowerShell.exe'),
               "-NoLogo", "-NonInteractive",  # Do not print headers
               "-Command", "-"]  # Listen commands from stdin
        startupinfo = sp.STARTUPINFO()
        startupinfo.dwFlags |= sp.STARTF_USESHOWWINDOW
        self.popen = sp.Popen(cmd, stdout=sp.PIPE, stdin=sp.PIPE, stderr=sp.STDOUT, startupinfo=startupinfo)
        self.coding = coding

    def __enter__(self):
        return self

    def __exit__(self, a, b, c):
        self.popen.kill()

    def run(self, cmd, timeout=15):
        b_cmd = cmd.encode(encoding=self.coding)
        try:
            b_outs, errs = self.popen.communicate(b_cmd, timeout=timeout)
        except sp.TimeoutExpired:
            self.popen.kill()
            b_outs, errs = self.popen.communicate()
        outs = b_outs.decode(encoding=self.coding)
        return outs, errs

    @staticmethod
    def _where(filename, dirs=None, env="PATH"):
        """Find file in current dir, in deep_lookup cache or in system path"""
        if dirs is None:
            dirs = []
        if not isinstance(dirs, list):
            dirs = [dirs]
        if glob(filename):
            return filename
        paths = [os.curdir] + os.environ[env].split(os.path.pathsep) + dirs
        try:
            return next(os.path.normpath(match)
                        for path in paths
                        for match in glob(os.path.join(path, filename))
                        if match)
        except (StopIteration, RuntimeError):
            raise IOError("File not found: %s" % filename)


## 获取当前CPU温度
def get_cpu_temperature():
    with PowerShell('GBK') as ps:
        outs= ps.run('gwmi msacpi_thermalzonetemperature -namespace "root/wmi"')
        # print('[*] outs:',outs[0])

        try:
            for i in outs[0].split('\r\n'):
                if 'CurrentTemperature' in i:
                    # print(i)
                    cpu_temperature = int(int(i.split(':')[1].strip())/10 - 273.15)
                    print('[*] cpu_temperature:',cpu_temperature)
                    return cpu_temperature
                else:
                    pass
        except Exception as e:
            pass


## 获取当前CPU占用百分比
def get_cpu_percent():
    dos_cmd = 'wmic cpu get loadpercentage'
    cpu_percent = os.popen(dos_cmd).read().split(' ')[2].strip()
    print('[*] cpu_percent:',cpu_percent)
    return cpu_percent


## 获取当前内存占用百分比
def get_mem_percent():
    ## 总内存单位是b,而剩余内存单位是kb
    dos_cmd = 'wmic ComputerSystem get TotalPhysicalMemory'
    mem_total = os.popen(dos_cmd).read().split(' ')[2].strip()
    # print('[*] mem_total:',mem_total)

    dos_cmd = 'wmic OS get FreePhysicalMemory'
    mem_free = os.popen(dos_cmd).read().split(' ')[2].strip()
    # print('[*] mem_free:',mem_free)

    mem_percent = int((1 - int(mem_free)/(int(mem_total)/1024)) *100)
    print('[*] mem_percent:',mem_percent)
    return mem_percent

## 获取当前硬盘信息
def get_disk_info():
    ## wmic LOGICALDISK WHERE MEDIATYPE='12' GET DESCRIPTION,DEVICEID,FILESYSTEM,SIZE,FREESPACE
    ## C盘-SIZE
    dos_cmd = "wmic LOGICALDISK WHERE DEVICEID='C:' GET SIZE"
    try:
        if re.findall(r'([0-9]{5,})',os.popen(dos_cmd).read()):
            disk_c_size = re.findall(r'([0-9]{5,})',os.popen(dos_cmd).read())[0]
    except Exception as e:
        pass

    disk_c_size = int(int(disk_c_size)/1024/1024/1024)
    print('[*] disk_c_size:',disk_c_size)

    ## C盘-FREESPACE
    dos_cmd = "wmic LOGICALDISK WHERE DEVICEID='C:' GET FREESPACE"
    try:
        if re.findall(r'([0-9]{5,})',os.popen(dos_cmd).read()):
            disk_c_free = re.findall(r'([0-9]{5,})',os.popen(dos_cmd).read())[0]
    except Exception as e:
        pass
    disk_c_free = int(int(disk_c_free)/1024/1024/1024)
    print('[*] disk_c_free:',disk_c_free)

    ## D 盘-SIZE
    dos_cmd = "wmic LOGICALDISK WHERE DEVICEID='D:' GET SIZE"
    try:
        if re.findall(r'([0-9]{5,})',os.popen(dos_cmd).read()):
            disk_d_size = re.findall(r'([0-9]{5,})',os.popen(dos_cmd).read())[0]
    except Exception as e:
        pass
    disk_d_size = int(int(disk_d_size)/1024/1024/1024)
    print('[*] disk_d_size:',disk_d_size)

    ## D盘-FREESPACE
    dos_cmd = "wmic LOGICALDISK WHERE DEVICEID='D:' GET FREESPACE"
    try:
        if re.findall(r'([0-9]{5,})',os.popen(dos_cmd).read()):
            disk_d_free = re.findall(r'([0-9]{5,})',os.popen(dos_cmd).read())[0]
    except Exception as e:
        pass
    disk_d_free = int(int(disk_d_free)/1024/1024/1024)
    print('[*] disk_d_free:',disk_d_free)

    return(disk_c_size,disk_c_free,disk_d_size,disk_d_free)


## Windows监控告警
def win_monitor_alert():
    ## 获取当前CPU温度
    cpu_temperature = get_cpu_temperature()
    ## 获取当前CPU占用百分比
    cpu_percent = get_cpu_percent()
    ## 获取当前内存占用百分比
    mem_percent = get_mem_percent()
    ## 获取当前硬盘信息
    disk_info = get_disk_info()
    disk_c_size = disk_info[0]
    disk_c_free = disk_info[1]
    disk_d_size = disk_info[2]
    disk_d_free = disk_info[3]


## 测试模块
def test_module():
    ## 获取当前硬盘信息
    disk_info = get_disk_info()


## 设定参数
def parse_args():
    parser = argparse.ArgumentParser(description = '==================== Python 主机监控 ====================')
    parser.add_argument('-t', '--test_module', help='测试模块', action='store_true')
    parser.add_argument('-w', '--win_monitor_alert', help='Windows监控告警', action='store_true')
    return parser.parse_args()


## 主函数部分
def main(): 
    ## 显示帮助命令
    if len(sys.argv) == 1:
        sys.argv.append('-h')
    
    args = parse_args()
    ## 测试模块
    if args.test_module:
        print('\n[*] 测试模块')
        test_module()

    ## Windows监控告警
    elif args.win_monitor_alert:
        print('\n[*] Windows监控告警')
        win_monitor_alert()

if __name__ == "__main__":
    main()
  • 0
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值