python获取linux磁盘信息_python 获取linux磁盘信息 - CSDN
精华内容
参与话题
  • python写的抓取linux系统主要信息的脚本,主要就是内存,硬盘、CPU之类的信息。   内存信息 / meminfo 返回dict #!/usr/bin/env python def memory_stat(): mem = {} f = open("/proc/meminfo&...

     python写的抓取linux系统主要信息的脚本,主要就是内存,硬盘、CPU之类的信息。

     

    1. 内存信息 / meminfo 
    2. 返回dict 
    3. #!/usr/bin/env python 
    4. def memory_stat(): 
    5.     mem = {} 
    6.     f = open("/proc/meminfo"
    7.     lines = f.readlines() 
    8.     f.close() 
    9.     for line in lines: 
    10.         if len(line) < 2: continue 
    11.         name = line.split(':')[0] 
    12.         var = line.split(':')[1].split()[0] 
    13.         mem[name] = long(var) * 1024.0 
    14.     mem['MemUsed'] = mem['MemTotal'] - mem['MemFree'] - mem['Buffers'] - mem['Cached'
    15.     return mem 
    16.  
    17. CPU信息 / cpuinfo 
    18. 返回list,每核心一dict 
    19. #!/usr/bin/env python 
    20. def cpu_stat(): 
    21.     cpu = [] 
    22.     cpuinfo = {} 
    23.     f = open("/proc/cpuinfo"
    24.     lines = f.readlines() 
    25.     f.close() 
    26.     for line in lines: 
    27.         if line == 'n'
    28.             cpu.append(cpuinfo) 
    29.             cpuinfo = {} 
    30.         if len(line) < 2: continue 
    31.         name = line.split(':')[0].rstrip() 
    32.         var = line.split(':')[1] 
    33.         cpuinfo[name] = var 
    34.     return  
    35.  
    36. cpu负载信息 / loadavg 
    37. 返回dict 
    38. #!/usr/bin/env python 
    39. def load_stat(): 
    40.     loadavg = {} 
    41.     f = open("/proc/loadavg"
    42.     con = f.read().split() 
    43.     f.close() 
    44.     loadavg['lavg_1']=con[0] 
    45.     loadavg['lavg_5']=con[1] 
    46.     loadavg['lavg_15']=con[2] 
    47.     loadavg['nr']=con[3] 
    48.     loadavg['last_pid']=con[4] 
    49.     return loadavg 
    50.  
    51. 运转时间 / Uptime 
    52. 返回dict 
    53. #!/usr/bin/env python 
    54. def uptime_stat(): 
    55.     uptime = {} 
    56.     f = open("/proc/uptime"
    57.     con = f.read().split() 
    58.     f.close() 
    59.     all_sec = float(con[0]) 
    60.     MINUTE,HOUR,DAY = 60,3600,86400 
    61.     uptime['day'] = int(all_sec / DAY ) 
    62.     uptime['hour'] = int((all_sec % DAY) / HOUR) 
    63.     uptime['minute'] = int((all_sec % HOUR) / MINUTE) 
    64.     uptime['second'] = int(all_sec % MINUTE) 
    65.     uptime['Free rate'] = float(con[1]) / float(con[0]) 
    66.     return uptime 
    67.  
    68. 获取网卡流量信息 /proc/net/dev 
    69. 返回dict,单位byte 
    70. #!/usr/bin/env python 
    71. def net_stat(): 
    72.     net = [] 
    73.     f = open("/proc/net/dev"
    74.     lines = f.readlines() 
    75.     f.close() 
    76.     for line in lines[2:]: 
    77.         con = line.split() 
    78.         ""
    79.         intf = {} 
    80.         intf['interface'] = con[0].lstrip(":"
    81.         intf['ReceiveBytes'] = int(con[1]) 
    82.         intf['ReceivePackets'] = int(con[2]) 
    83.         intf['ReceiveErrs'] = int(con[3]) 
    84.         intf['ReceiveDrop'] = int(con[4]) 
    85.         intf['ReceiveFifo'] = int(con[5]) 
    86.         intf['ReceiveFrames'] = int(con[6]) 
    87.         intf['ReceiveCompressed'] = int(con[7]) 
    88.         intf['ReceiveMulticast'] = int(con[8]) 
    89.         intf['TransmitBytes'] = int(con[9]) 
    90.         intf['TransmitPackets'] = int(con[10]) 
    91.         intf['TransmitErrs'] = int(con[11]) 
    92.         intf['TransmitDrop'] = int(con[12]) 
    93.         intf['TransmitFifo'] = int(con[13]) 
    94.         intf['TransmitFrames'] = int(con[14]) 
    95.         intf['TransmitCompressed'] = int(con[15]) 
    96.         intf['TransmitMulticast'] = int(con[16]) 
    97.         ""
    98.         intf = dict( 
    99.             zip( 
    100.                 ( 'interface','ReceiveBytes','ReceivePackets'
    101.                   'ReceiveErrs','ReceiveDrop','ReceiveFifo'
    102.                   'ReceiveFrames','ReceiveCompressed','ReceiveMulticast'
    103.                   'TransmitBytes','TransmitPackets','TransmitErrs'
    104.                   'TransmitDrop''TransmitFifo','TransmitFrames'
    105.                   'TransmitCompressed','TransmitMulticast' ), 
    106.                 ( con[0].rstrip(":"),int(con[1]),int(con[2]), 
    107.                   int(con[3]),int(con[4]),int(con[5]), 
    108.                   int(con[6]),int(con[7]),int(con[8]), 
    109.                   int(con[9]),int(con[10]),int(con[11]), 
    110.                   int(con[12]),int(con[13]),int(con[14]), 
    111.                   int(con[15]),int(con[16]), ) 
    112.             ) 
    113.         ) 
    114.  
    115.         net.append(intf) 
    116.     return net 
    117.  
    118. 磁盘空间使用 
    119. 使用内置python内置函数,返回dict,单位byte 
    120. #!/usr/bin/env python 
    121. def disk_stat(): 
    122.     import os 
    123.     hd={} 
    124.     disk = os.statvfs("/"
    125.     hd['available'] = disk.f_bsize * disk.f_bavail 
    126.     hd['capacity'] = disk.f_bsize * disk.f_blocks 
    127.     hd['used'] = disk.f_bsize * disk.f_bfree 
    128.     return hd 

     

    展开全文
  • python语言获取linux磁盘使用情况

    万次阅读 2012-02-14 16:07:06
    我面对两个需要解决的问题,首先为统计磁盘,其次为插入数据库,两件事分开做没什么大的难度,但要求统计并将结果存入数据库却也不是很轻易的事情,忙活了2天终于使用python将其搞定,以下将分享本人解决该问题的...

         最近项目需求,做统计磁盘使用情况的自动运行脚本,该脚本还需将统计结果更新到数据库中。我面对两个需要解决的问题,首先为统计磁盘,其次为插入数据库,两件事分开做没什么大的难度,但要求统计并将结果存入数据库却也不是很轻易的事情,忙活了2天终于使用python将其搞定,以下将分享本人解决该问题的心得。

        首先解决统计的问题,google后找到解决方案,贴代码

        来自 http://stackoverflow.com/questions/4260116/disk-usage-in-linux-using-python

    //导入库
    import os
    from collections import namedtuple
    
    disk_ntuple = namedtuple('partition',  'device mountpoint fstype')
    usage_ntuple = namedtuple('usage',  'total used free percent')
    //获取当前操作系统下所有磁盘
    def disk_partitions(all=False):
        """Return all mountd partitions as a nameduple.
        If all == False return phyisical partitions only.
        """
        phydevs = []
        f = open("/proc/filesystems", "r")
        for line in f:
            if not line.startswith("nodev"):
                phydevs.append(line.strip())
    
        retlist = []
        f = open('/etc/mtab', "r")
        for line in f:
            if not all and line.startswith('none'):
                continue
            fields = line.split()
            device = fields[0]
            mountpoint = fields[1]
            fstype = fields[2]
            if not all and fstype not in phydevs:
                continue
            if device == 'none':
                device = ''
            ntuple = disk_ntuple(device, mountpoint, fstype)
            retlist.append(ntuple)
        return retlist
    //统计某磁盘使用情况,返回对象
    def disk_usage(path):
        """Return disk usage associated with path."""
        st = os.statvfs(path)
        free = (st.f_bavail * st.f_frsize)
        total = (st.f_blocks * st.f_frsize)
        used = (st.f_blocks - st.f_bfree) * st.f_frsize
        try:
            percent = ret = (float(used) / total) * 100
        except ZeroDivisionError:
            percent = 0
        # NB: the percentage is -5% than what shown by df due to
        # reserved blocks that we are currently not considering:
        # http://goo.gl/sWGbH
        return usage_ntuple(total, used, free, round(percent, 1))
    
    
    我将 disk_partitions 函数的返回数组中每个值循环传入 disk_usage,就能获得磁盘的诸如总容量,已使用容量和剩余容量,由于计算原因,有5%的误差。

    当然,如果不想获取所有的磁盘,而仅仅获取特定的磁盘,可调用python的函数disk_ntuple(device, mountpoint, fstype),三个参数分别为,设备路径,比如/dev/sda1,第二个参数为挂载路径,如/home ,第三个参数为磁盘的文件系统类型,返回值的属性mountpoint可以作为disk_usage的参数来获得磁盘使用情况,比如返回值为a,可以这样调用disk_usage(a.mountpoint)。


    展开全文
  • 又可获取linux系统及硬件信息 一站式,全平台! 文章底部直接贴完整代码,先上介绍和函数说明 system-info 基于python3的linux和windows系统信息api linux and windows system information api Github: ...

    即可获取windows系统及硬件信息

    又可获取linux系统及硬件信息

    一站式,全平台!

    文章底部直接贴完整代码,先上介绍和函数说明


    system-info

    基于python3的linux和windows系统信息api
    linux and windows system information api

    Github: https://github.com/Pure-Peace/system-info

    based on: python3.8(基本python3以上即可)


    所有api均支持linux和windows
    All apis support linux and windows


    api列表:

    CpuConstants
    ExecShellUnix
    GetBootTime
    GetCpuConstants
    GetCpuInfo
    GetDiskInfo
    GetDiskInfoUnix
    GetDiskInfoWindows
    GetErrorInfo
    GetFullSystemData
    GetIoRead
    GetIoReadWrite
    GetIoWrite
    GetLoadAverage
    GetMemInfo
    GetMemInfoUnix
    GetMemInfoWindows
    GetNetWork
    GetRegValue
    GetSystemInfo
    GetSystemVersion
    GetSystemVersionUnix
    GetSystemVersionWindows
    ToSizeInt
    ToSizeString
    UNIX
    cpuConstants
    md5
    readFile
    

    api说明:

    当前系统网络使用情况:上传下载速率,收发包

    GetNetWork()
    

    both

    {
    	'up': 1.54,
    	'down': 0.37,
    	'upTotal': 87688289,
    	'downTotal': 336439316,
    	'downPackets': 397399,
    	'upPackets': 262468
    }
    

    当前系统磁盘IO情况:IO读写

    GetIoReadWrite()
    

    both

    {'write': 1003332, 'read': 1466368}
    

    当前系统CPU常量

    GetCpuConstants()
    

    windows

    {'cpu_count': 1, 'cpu_name': 'AMD Ryzen 5 2500U with Radeon Vega Mobile Gfx  ', 'cpu_core': 4, 'cpu_threads': 8}
    

    linux

    {'cpu_count': 1, 'cpu_name': 'Intel(R) Xeon(R) Platinum 8269CY CPU @ 2.50GHz', 'cpu_core': 1, 'cpu_threads': 1}
    

    当前系统CPU信息、使用率

    GetCpuInfo()
    

    windows

    {
    	'used': 17.2,
    	'used_list': [23.8, 12.2, 19.6, 10.2, 20.3, 6.2, 12.6, 30.3],
    	'cpu_count': 1,
    	'cpu_name': 'AMD Ryzen 5 2500U with Radeon Vega Mobile Gfx  ',
    	'cpu_core': 4,
    	'cpu_threads': 8
    }
    

    linux

    {
    	'used': 2.0,
    	'used_list': [3.4],
    	'cpu_count': 1,
    	'cpu_name': 'Intel(R) Xeon(R) Platinum 8269CY CPU @ 2.50GHz',
    	'cpu_core': 1,
    	'cpu_threads': 1
    }
    

    当前系统负载信息

    GetLoadAverage()
    

    windows

    {
    	'one': 0,
    	'five': 0,
    	'fifteen': 0,
    	'max': 16,
    	'limit': 16,
    	'safe': 12.0
    }
    

    linux

    {
    	'one': 0.46,
    	'five': 0.18,
    	'fifteen': 0.14,
    	'max': 2,
    	'limit': 2,
    	'safe': 1.5
    }
    

    当前系统内存使用情况(linux比windows多了cached和buffers)

    GetMemInfo()
    

    windows

    {
    	'memTotal': 7069,
    	'memFree': 1202,
    	'memRealUsed': 5866,
    	'menUsedPercent': '82.98'
    }
    

    linux

    {
    	'memTotal': 1838,
    	'memFree': 181,
    	'memBuffers': 25,
    	'memCached': 448,
    	'memRealUsed': 1184,
    	'memUsedPercent': 64.41784548422198
    }
    

    当前系统磁盘信息

    GetDiskInfo()
    

    windows

    [{'path': 'C:/',
      'size': {'total': 85899341824,
       'used': 84512485376,
       'free': 1386856448,
       'percent': 98.4},
      'fstype': 'NTFS',
      'inodes': False},
     {'path': 'D:/',
      'size': {'total': 413524815872,
       'used': 367597920256,
       'free': 45926895616,
       'percent': 88.9},
      'fstype': 'NTFS',
      'inodes': False}]
    

    linux

    [{
    	'path': '/',
    	'size': ['50G', '16G', '32G', '33%'],
    	'inodes': ['3276800', '261498', '3015302', '8%']
    }]
    

    获取系统注册表信息(仅windows可用)

    GetRegValue(key: str, subkey: str, value: str)
    
        '''
      获取系统注册表信息
    
      Parameters
      ----------
      key : str
          类型.
      subkey : str
          路径.
      value : str
          key.
    
      Returns
      -------
      value : Any
          DESCRIPTION.
    
      '''
    

    获取系统版本信息

    GetSystemVersion()
    

    windows

    Windows 10 Home China (build 18362) x64 (Py3.8.5)
    

    linux

    CentOS  7.6.1810(Py 3.8.5)
    

    获取系统启动时间及运行时间

    GetBootTime()
    

    both

    {'timestamp': 1597574445.835271,
     'runtime': 33396.16829442978,
     'datetime': '2020-08-17 03:57:22'}
    

    获取全部系统信息

    GetFullSystemData()
    

    windows

    {
    	'cpu': {
    		'used': 16.0,
    		'used_list': [29.0, 16.4, 30.5, 13.9, 28.1, 16.8, 24.0, 26.7],
    		'cpu_count': 1,
    		'cpu_name': 'AMD Ryzen 5 2500U with Radeon Vega Mobile Gfx  ',
    		'cpu_core': 4,
    		'cpu_threads': 8
    	},
    	'load': {
    		'one': 0,
    		'five': 0,
    		'fifteen': 0,
    		'max': 16,
    		'limit': 16,
    		'safe': 12.0
    	},
    	'mem': {
    		'memTotal': 7069,
    		'memFree': 1181,
    		'memRealUsed': 5888,
    		'menUsedPercent': '83.29'
    	},
    	'disk': [{
    		'path': 'C:/',
    		'size': {
    			'total': 85899341824,
    			'used': 84515794944,
    			'free': 1383546880,
    			'percent': 98.4
    		},
    		'fstype': 'NTFS',
    		'inodes': False
    	}, {
    		'path': 'D:/',
    		'size': {
    			'total': 413524815872,
    			'used': 367597862912,
    			'free': 45926952960,
    			'percent': 88.9
    		},
    		'fstype': 'NTFS',
    		'inodes': False
    	}],
    	'network': {
    		'up': 1.84,
    		'down': 2.69,
    		'upTotal': 92363508,
    		'downTotal': 342344006,
    		'downPackets': 409006,
    		'upPackets': 271275
    	},
    	'io': {
    		'write': 1277171,
    		'read': 38696960
    	},
    	'boot': {
    		'timestamp': 1597574445.966399,
    		'runtime': 34064.19006037712,
    		'datetime': '2020-08-17 04:08:30'
    	},
    	'time': 1597608510.1564593
    }
    

    linux

    {
    	'cpu': {
    		'used': 6.0,
    		'used_list': [3.4],
    		'cpu_count': 1,
    		'cpu_name': 'Intel(R) Xeon(R) Platinum 8269CY CPU @ 2.50GHz',
    		'cpu_core': 1,
    		'cpu_threads': 1
    	},
    	'load': {
    		'one': 0.59,
    		'five': 0.49,
    		'fifteen': 0.28,
    		'max': 2,
    		'limit': 2,
    		'safe': 1.5
    	},
    	'mem': {
    		'memTotal': 1838,
    		'memFree': 180,
    		'memBuffers': 26,
    		'memCached': 448,
    		'memRealUsed': 1184,
    		'memUsedPercent': 64.41784548422198
    	},
    	'disk': [{
    		'path': '/',
    		'size': ['50G', '16G', '32G', '33%'],
    		'inodes': ['3276800', '261498', '3015302', '8%']
    	}],
    	'network': {
    		'up': 0.0,
    		'down': 0.0,
    		'upTotal': 606720149,
    		'downTotal': 479946863,
    		'downPackets': 1431369,
    		'upPackets': 1305962
    	},
    	'io': {
    		'write': 0,
    		'read': 0
    	},
    	'boot': {
    		'timestamp': 1597435339.0,
    		'runtime': 175312.03097391129,
    		'datetime': '2020-08-17 04:44:11'
    	},
    	'time': 1597610651.0309963
    }
    

    Author

    Pure-Peace

    代码

    systemInfo.py
    
    # -*- coding: utf-8 -*-
    '''
    @name: 系统信息 / SystemInfo
    @author: PurePeace
    @time: 2020年8月17日
    @version: 0.1
    '''
    
    from typing import List, Dict, Any
    
    import os
    import time
    import psutil
    import platform
    import hashlib
    import re
    import sys
    
    
    from cachelib import SimpleCache
    cache = SimpleCache()
    
    
    UNIX: bool = os.name == 'posix'
    SYS: str = platform.system()
    
    
    class CpuConstants:
        def __init__(self):
            '''
            初始化CPU常量(多平台)
    
            Returns
            -------
            self.
    
            '''
            self.WMI = None
            self.initialed: bool = False
            self.cpuList: list = [] # windows only
    
            self.cpuCount: int = 0 # 物理cpu数量
            self.cpuCore: int = 0 # cpu物理核心数
            self.cpuThreads: int = 0 # cpu逻辑核心数
            self.cpuName: str = '' # cpu型号
    
            self.Update(True)
    
    
        def Update(self, update: bool = False) -> None:
            '''
            更新cpu数据
    
            Returns
            -------
            None.
    
            '''
            if UNIX: self.GetCpuConstantsUnix(update)
            else: self.GetCpuConstantsWindows(update)
    
            self.initialed: bool = True
    
    
        @property
        def getDict(self) -> Dict[int, str]:
            '''
            以字典格式获取当前cpu常量
    
            Returns
            -------
            Dict[int, str]
                DESCRIPTION.
    
            '''
            if not self.initialed: self.Update()
            return {
                'cpu_count': self.cpuCount,
                'cpu_name': self.cpuName,
                'cpu_core': self.cpuCore,
                'cpu_threads': self.cpuThreads
            }
    
    
        def GetCpuConstantsUnix(self, update: bool = False) -> None:
            '''
            获取unix下的cpu信息
    
            Parameters
            ----------
            update : bool, optional
                DESCRIPTION. The default is False.
    
            Returns
            -------
            None
                DESCRIPTION.
    
            '''
            if update or not self.initialed:
                ids: list = re.findall("physical id.+", readFile('/proc/cpuinfo'))
    
                # 物理cpu个数
                self.cpuCount: int = len(set(ids))
    
                # cpu型号(名称)
                self.cpuName: str = self.getCpuTypeUnix()
    
    
                self.GetCpuConstantsBoth()
    
    
        def InitWmi(self) -> None:
            '''
            初始化wmi(for windows)
    
            Returns
            -------
            None
                DESCRIPTION.
    
            '''
            import wmi
            self.WMI = wmi.WMI()
    
    
        def GetCpuConstantsBoth(self, update: bool = False) -> None:
            '''
            获取多平台共用的cpu信息
    
            Parameters
            ----------
            update : bool, optional
                强制更新数据. The default is False.
    
            Returns
            -------
            None
                DESCRIPTION.
    
            '''
            if update or not self.initialed:
    
                # cpu逻辑核心数
                self.cpuThreads: int = psutil.cpu_count()
    
                # cpu物理核心数
                self.cpuCore: int = psutil.cpu_count(logical=False)
    
    
        def GetCpuConstantsWindows(self, update: bool = False) -> None:
            '''
            获取windows平台的cpu信息
    
            Parameters
            ----------
            update : bool, optional
                强制更新数据. The default is False.
    
            Returns
            -------
            None
                DESCRIPTION.
    
            '''
            if update or not self.initialed:
    
                # 初始化wmi
                if self.WMI == None: self.InitWmi()
    
                # cpu列表
                self.cpuList: list = self.WMI.Win32_Processor()
    
                # 物理cpu个数
                self.cpuCount: int = len(self.cpuList)
    
                # cpu型号(名称)
                self.cpuName: str = self.cpuList[0].Name
    
    
                self.GetCpuConstantsBoth()
    
    
        @staticmethod
        def getCpuTypeUnix() -> str:
            '''
            获取CPU型号(unix)
    
            Returns
            -------
            str
                CPU型号.
    
            '''
            cpuinfo: str = readFile('/proc/cpuinfo')
            rep: str = 'model\s+name\s+:\s+(.+)'
            tmp = re.search(rep,cpuinfo,re.I)
            cpuType: str = ''
            if tmp:
                cpuType: str = tmp.groups()[0]
            else:
                cpuinfo = ExecShellUnix('LANG="en_US.UTF-8" && lscpu')[0]
                rep = 'Model\s+name:\s+(.+)'
                tmp = re.search(rep,cpuinfo,re.I)
                if tmp: cpuType = tmp.groups()[0]
            return cpuType
    
    
    def GetCpuInfo(interval: int = 1) -> Dict[str, Any]:
        '''
        获取CPU信息
    
        Parameters
        ----------
        interval : int, optional
            DESCRIPTION. The default is 1.
    
        Returns
        -------
        Dict[float, list, dict]
            DESCRIPTION.
    
        '''
        time.sleep(0.5)
    
    
        # cpu总使用率
        used: float = psutil.cpu_percent(interval)
    
        # 每个逻辑cpu使用率
        usedList: List[float] = psutil.cpu_percent(percpu=True)
    
    
        return {'used': used, 'used_list': usedList, **cpuConstants.getDict}
    
    
    def readFile(filename: str) -> str:
        '''
        读取文件内容
    
        Parameters
        ----------
        filename : str
            文件名.
    
        Returns
        -------
        str
            文件内容.
    
        '''
        try:
            with open(filename, 'r', encoding='utf-8') as file: return file.read()
        except:
            pass
    
        return ''
    
    
    def GetLoadAverage() -> dict:
        '''
        获取服务器负载状态(多平台)
    
        Returns
        -------
        dict
            DESCRIPTION.
    
        '''
        try: c: list = os.getloadavg()
        except: c: list = [0,0,0]
        data: dict = {i: c[idx] for idx, i in enumerate(('one', 'five', 'fifteen'))}
        data['max'] = psutil.cpu_count() * 2
        data['limit'] = data['max']
        data['safe'] = data['max'] * 0.75
        return data
    
    
    def GetMemInfo() -> dict:
        '''
        获取内存信息(多平台)
    
        Returns
        -------
        dict
            DESCRIPTION.
    
        '''
        if UNIX: return GetMemInfoUnix()
        return GetMemInfoWindows()
    
    
    def GetMemInfoUnix() -> Dict[str, int]:
        '''
        获取内存信息(unix)
    
        Returns
        -------
        dict
            DESCRIPTION.
    
        '''
        mem = psutil.virtual_memory()
        memInfo: dict = {
            'memTotal': ToSizeInt(mem.total, 'MB'),
            'memFree': ToSizeInt(mem.free, 'MB'),
            'memBuffers': ToSizeInt(mem.buffers, 'MB'),
            'memCached': ToSizeInt(mem.cached, 'MB'),
        }
        memInfo['memRealUsed'] = \
            memInfo['memTotal'] - \
            memInfo['memFree'] - \
            memInfo['memBuffers'] - \
            memInfo['memCached']
    
        memInfo['memUsedPercent'] = memInfo['memRealUsed'] / memInfo['memTotal'] * 100
    
        return memInfo
    
    
    def GetMemInfoWindows() -> dict:
        '''
        获取内存信息(windows)
    
        Returns
        -------
        dict
            DESCRIPTION.
    
        '''
        mem = psutil.virtual_memory()
        memInfo: dict = {
            'memTotal': ToSizeInt(mem.total, 'MB'),
            'memFree': ToSizeInt(mem.free, 'MB'),
            'memRealUsed': ToSizeInt(mem.used, 'MB'),
            'menUsedPercent': mem.used / mem.total * 100
        }
    
        return memInfo
    
    
    def ToSizeInt(byte: int, target: str) -> int:
        '''
        将字节大小转换为目标单位的大小
    
        Parameters
        ----------
        byte : int
            int格式的字节大小(bytes size)
        target : str
            目标单位,str.
    
        Returns
        -------
        int
            转换为目标单位后的字节大小.
    
        '''
        return int(byte/1024**(('KB','MB','GB','TB').index(target) + 1))
    
    
    def ToSizeString(byte: int) -> str:
        '''
        获取字节大小字符串
    
        Parameters
        ----------
        byte : int
            int格式的字节大小(bytes size).
    
        Returns
        -------
        str
            自动转换后的大小字符串,如:6.90 GB.
    
        '''
        units: tuple = ('b','KB','MB','GB','TB')
        re = lambda: '{:.2f} {}'.format(byte, u)
        for u in units:
            if byte < 1024: return re()
            byte /= 1024
        return re()
    
    
    def GetDiskInfo() -> list:
        '''
        获取磁盘信息(多平台)
    
        Returns
        -------
        list
            列表.
    
        '''
        try:
            if UNIX: return GetDiskInfoUnix()
            return GetDiskInfoWindows()
        except Exception as err:
            print('获取磁盘信息异常(unix: {}):'.format(UNIX), err)
            return []
    
    
    def GetDiskInfoWindows() -> list:
        '''
        获取磁盘信息Windows
    
        Returns
        -------
        diskInfo : list
            列表.
    
        '''
        diskIo: list = psutil.disk_partitions()
        diskInfo: list = []
        for disk in diskIo:
            tmp: dict = {}
            try:
                tmp['path'] = disk.mountpoint.replace("\\","/")
                usage = psutil.disk_usage(disk.mountpoint)
                tmp['size'] = {
                    'total': usage.total,
                    'used': usage.used,
                    'free': usage.free,
                    'percent': usage.percent
                }
                tmp['fstype'] = disk.fstype
                tmp['inodes'] = False
                diskInfo.append(tmp)
            except:
                pass
        return diskInfo
    
    
    def GetDiskInfoUnix() -> list:
         '''
        获取硬盘分区信息(unix)
    
        Returns
        -------
        list
            DESCRIPTION.
    
        '''
         temp: list = (
             ExecShellUnix("df -h -P|grep '/'|grep -v tmpfs")[0]).split('\n')
         tempInodes: list = (
             ExecShellUnix("df -i -P|grep '/'|grep -v tmpfs")[0]).split('\n')
         diskInfo: list = []
         n: int = 0
         cuts: list = [
             '/mnt/cdrom',
             '/boot',
             '/boot/efi',
             '/dev',
             '/dev/shm',
             '/run/lock',
             '/run',
             '/run/shm',
             '/run/user'
         ]
         for tmp in temp:
             n += 1
             try:
                 inodes: list = tempInodes[n-1].split()
                 disk: list = tmp.split()
                 if len(disk) < 5: continue
                 if disk[1].find('M') != -1: continue
                 if disk[1].find('K') != -1: continue
                 if len(disk[5].split('/')) > 10: continue
                 if disk[5] in cuts: continue
                 if disk[5].find('docker') != -1: continue
                 arr = {}
                 arr['path'] = disk[5]
                 tmp1 = [disk[1],disk[2],disk[3],disk[4]]
                 arr['size'] = tmp1
                 arr['inodes'] = [inodes[1],inodes[2],inodes[3],inodes[4]]
                 diskInfo.append(arr)
             except Exception as ex:
                 print('信息获取错误:', str(ex))
                 continue
         return diskInfo
    
    
    
    def md5(strings: str) -> str:
        '''
        生成md5
    
        Parameters
        ----------
        strings : TYPE
            要进行hash处理的字符串
    
        Returns
        -------
        str[32]
            hash后的字符串.
    
        '''
    
        m = hashlib.md5()
        m.update(strings.encode('utf-8'))
        return m.hexdigest()
    
    
    def GetErrorInfo() -> str:
        '''
        获取traceback中的错误
    
        Returns
        -------
        str
            DESCRIPTION.
    
        '''
        import traceback
        errorMsg = traceback.format_exc()
        return errorMsg
    
    
    def ExecShellUnix(cmdstring: str, shell=True):
        '''
        执行Shell命令(Unix)
    
        Parameters
        ----------
        cmdstring : str
            DESCRIPTION.
        shell : TYPE, optional
            DESCRIPTION. The default is True.
    
        Returns
        -------
        a : TYPE
            DESCRIPTION.
        e : TYPE
            DESCRIPTION.
    
        '''
        a: str = ''
        e: str = ''
        import subprocess,tempfile
    
        try:
            rx: str = md5(cmdstring)
            succ_f = tempfile.SpooledTemporaryFile(
                max_size = 4096,
                mode = 'wb+',
                suffix = '_succ',
                prefix = 'btex_' + rx ,
                dir = '/dev/shm'
            )
            err_f = tempfile.SpooledTemporaryFile(
                max_size = 4096,
                mode = 'wb+',
                suffix = '_err',
                prefix = 'btex_' + rx ,
                dir = '/dev/shm'
            )
            sub = subprocess.Popen(
                cmdstring,
                close_fds = True,
                shell = shell,
                bufsize = 128,
                stdout = succ_f,
                stderr = err_f
            )
            sub.wait()
            err_f.seek(0)
            succ_f.seek(0)
            a = succ_f.read()
            e = err_f.read()
            if not err_f.closed: err_f.close()
            if not succ_f.closed: succ_f.close()
        except Exception as err:
            print(err)
        try:
            if type(a) == bytes: a = a.decode('utf-8')
            if type(e) == bytes: e = e.decode('utf-8')
        except Exception as err:
            print(err)
    
        return a,e
    
    
    def GetNetWork() -> dict:
        '''
        获取系统网络信息
    
        Returns
        -------
        dict
            DESCRIPTION.
    
        '''
        networkIo: list = [0,0,0,0]
        cache_timeout: int = 86400
        try:
            networkIo = psutil.net_io_counters()[:4]
        except:
            pass
    
        otime = cache.get("otime")
        if not otime:
            otime = time.time()
            cache.set('up',networkIo[0],cache_timeout)
            cache.set('down',networkIo[1],cache_timeout)
            cache.set('otime',otime ,cache_timeout)
    
        ntime = time.time()
        networkInfo: dict = {'up': 0, 'down': 0}
        networkInfo['upTotal']   = networkIo[0]
        networkInfo['downTotal'] = networkIo[1]
        try:
            networkInfo['up'] = round(
                float(networkIo[0] - cache.get("up")) / 1024 / (ntime - otime),
                2
            )
            networkInfo['down'] = round(
                float(networkIo[1] - cache.get("down")) / 1024 / (ntime -  otime),
                2
            )
        except:
            pass
    
        networkInfo['downPackets'] = networkIo[3]
        networkInfo['upPackets'] = networkIo[2]
    
        cache.set('up',networkIo[0],cache_timeout)
        cache.set('down',networkIo[1],cache_timeout)
        cache.set('otime', time.time(),cache_timeout)
    
        return networkInfo
    
    
    def GetSystemInfo() -> dict:
        systemInfo: dict = {}
        systemInfo['cpu'] = GetCpuInfo()
        systemInfo['load'] = GetLoadAverage()
        systemInfo['mem'] = GetMemInfo()
        systemInfo['disk'] = GetDiskInfo()
    
        return systemInfo
    
    
    
    def GetIoReadWrite() -> Dict[str, int]:
        '''
        获取系统IO读写
    
        Returns
        -------
        dict
            DESCRIPTION.
    
        '''
        ioDisk = psutil.disk_io_counters()
        ioTotal: dict = {}
        ioTotal['write'] = GetIoWrite(ioDisk.write_bytes)
        ioTotal['read'] = GetIoRead(ioDisk.read_bytes)
        return ioTotal
    
    
    def GetIoWrite(ioWrite: int) -> int:
        '''
        获取IO写
    
        Parameters
        ----------
        ioWrite : TYPE
            DESCRIPTION.
    
        Returns
        -------
        int
            DESCRIPTION.
    
        '''
        diskWrite: int = 0
        oldWrite: int = cache.get('io_write')
        if not oldWrite:
            cache.set('io_write', ioWrite)
            return diskWrite;
    
        oldTime: float = cache.get('io_time')
        newTime: float = time.time()
        if not oldTime: oldTime = newTime
        ioEnd: int = (ioWrite - oldWrite)
        timeEnd: float = (time.time() - oldTime)
        if ioEnd > 0:
            if timeEnd < 1: timeEnd = 1
            diskWrite = ioEnd / timeEnd
        cache.set('io_write',ioWrite)
        cache.set('io_time',newTime)
        if diskWrite > 0: return int(diskWrite)
        return 0
    
    
    def GetIoRead(ioRead):
        '''
        读取IO读
    
        Parameters
        ----------
        ioRead : TYPE
            DESCRIPTION.
    
        Returns
        -------
        TYPE
            DESCRIPTION.
    
        '''
        diskRead: int = 0
        oldRead: int = cache.get('io_read')
        if not oldRead:
            cache.set('io_read',ioRead)
            return diskRead;
        oldTime: float = cache.get('io_time')
        newTime: float = time.time()
        if not oldTime: oldTime = newTime
        ioEnd: int = (ioRead - oldRead)
        timeEnd: float = (time.time() - oldTime)
        if ioEnd > 0:
            if timeEnd < 1: timeEnd = 1;
            diskRead = ioEnd / timeEnd;
        cache.set('io_read', ioRead)
        if diskRead > 0: return int(diskRead)
        return 0
    
    
    def GetRegValue(key: str, subkey: str, value: str) -> Any:
        '''
        获取系统注册表信息
    
        Parameters
        ----------
        key : str
            类型.
        subkey : str
            路径.
        value : str
            key.
    
        Returns
        -------
        value : Any
            DESCRIPTION.
    
        '''
        import winreg
        key = getattr(winreg, key)
        handle = winreg.OpenKey(key, subkey)
        (value, type) = winreg.QueryValueEx(handle, value)
        return value
    
    
    def GetSystemVersion() -> str:
        '''
        获取操作系统版本(多平台)
    
        Returns
        -------
        str
            DESCRIPTION.
    
        '''
        if UNIX: return GetSystemVersionUnix()
        return GetSystemVersionWindows()
    
    
    def GetSystemVersionWindows() -> str:
        '''
        获取操作系统版本(windows)
    
        Returns
        -------
        str
            DESCRIPTION.
    
        '''
        try:
            import platform
            bit: str = 'x86';
            if 'PROGRAMFILES(X86)' in os.environ: bit = 'x64'
    
            def get(key: str):
                return GetRegValue(
                    "HKEY_LOCAL_MACHINE",
                    "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion",
                    key
                )
    
            osName = get('ProductName')
            build = get('CurrentBuildNumber')
    
            version: str = '{} (build {}) {} (Py{})'.format(
                osName, build, bit, platform.python_version())
            return version
        except Exception as ex:
            print('获取系统版本失败,错误:' + str(ex))
            return '未知系统版本.'
    
    
    def GetSystemVersionUnix() -> str:
        '''
        获取系统版本(unix)
    
        Returns
        -------
        str
            系统版本.
    
        '''
        try:
            version: str = readFile('/etc/redhat-release')
            if not version:
                version = readFile(
                    '/etc/issue'
                ).strip().split("\n")[0].replace('\\n','').replace('\l','').strip()
            else:
                version = version.replace(
                    'release ',''
                ).replace('Linux','').replace('(Core)','').strip()
            v = sys.version_info
            return version + '(Py {}.{}.{})'.format(v.major, v.minor, v.micro)
        except Exception as err:
            print('获取系统版本失败,错误:', err)
            return '未知系统版本.'
    
    
    def GetBootTime() -> dict:
        '''
        获取当前系统启动时间
    
        Returns
        -------
        dict
            DESCRIPTION.
    
        '''
        bootTime: float = psutil.boot_time()
        return {
            'timestamp': bootTime,
            'runtime': time.time() - bootTime,
            'datetime': time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())
        }
    
    
    def GetCpuConstants() -> dict:
        '''
        获取CPU常量信息
    
        Parameters
        ----------
        cpuConstants : CpuConstants
            DESCRIPTION.
    
        Returns
        -------
        dict
            DESCRIPTION.
    
        '''
        return cpuConstants.getDict
    
    
    def GetFullSystemData() -> dict:
        '''
        获取完全的系统信息
    
        Returns
        -------
        dict
            DESCRIPTION.
    
        '''
        systemData: dict = {
            **GetSystemInfo(),
            'network': { **GetNetWork() },
            'io': { **GetIoReadWrite() },
            'boot': { **GetBootTime() },
            'time': time.time()
        }
        return systemData
    
    cpuConstants = CpuConstants()
    
    if __name__ == '__main__':
        print(GetFullSystemData())
        print(GetCpuConstants())
        print(GetSystemInfo())
        print(GetNetWork())
        print(GetIoReadWrite())
        
    

    !!!

    展开全文
  • 获取磁盘完整信息 [root@bogon python_auto]# vim disk.py !/usr/bin/env python import psutil disk = psutil.disk_partitions() #利用psutil模块的disk_partitions()方法 print disk 执行查看...

    获取磁盘完整信息

    [root@bogon python_auto]# vim disk.py

    !/usr/bin/env python

    import psutil

    disk = psutil.disk_partitions() #利用psutil模块的disk_partitions()方法

    print disk

    执行查看结果

    [root@bogon python_auto]# python disk.py
    [sdiskpart(device='/dev/sda2', mountpoint='/', fstype='ext4', opts='rw'), sdiskpart(device='/dev/sda1', mountpoint='/boot', fstype='ext4', opts='rw')]

    获取分区的使用情况

    [root@bogon python_auto]# vim disk.py

    !/usr/bin/env python

    import psutil

    disk = psutil.disk_partitions()

    partition = psutil.disk_usage('/')
    print partition

    执行查看结果

    [root@bogon python_auto]# python disk.py
    sdiskusage(total=18779398144, used=3674472448, free=14150983680, percent=19.600000000000001)
    [root@bogon python_auto]#

    获取磁盘总的IO个数、读写信息

    [root@bogon python_auto]# vim disk.py

    !/usr/bin/env python

    import psutil

    disk = psutil.disk_partitions()

    partition = psutil.disk_usage('/')

    print partition

    io = psutil.disk_io_counters()
    print io

    执行查看结果

    [root@bogon python_auto]# python disk.py
    sdiskio(read_count=245556, write_count=118038, read_bytes=5248733184, write_bytes=3704962048, read_time=1424144, write_time=3252612)
    [root@bogon python_auto]#

    获取单个分区io个数、读写信息。

    [root@bogon python_auto]# vim disk.py

    !/usr/bin/env python

    import psutil

    disk = psutil.disk_partitions()

    partition = psutil.disk_usage('/')

    print partition

    io = psutil.disk_io_counters()

    print io

    perdisk = psutil.disk_io_counters(perdisk=True)
    print perdisk

    执行查看结果
    [root@bogon python_auto]# python disk.py
    {'sda2': sdiskio(read_count=243109, write_count=117669, read_bytes=5193733120, write_bytes=3656708096, read_time=1409641, write_time=3249864), 'sda3': sdiskio(read_count=1223, write_count=466, read_bytes=10375168, write_bytes=49188864, read_time=10872, write_time=2831), 'sda1': sdiskio(read_count=1224, write_count=29, read_bytes=44624896, write_bytes=48128, read_time=3631, write_time=83)}
    [root@bogon python_auto]#

    可以看到磁盘每个分区的详细信息都有了。

    展开全文
  • 在日常运维或者迁移客户系统的时候我们需要快速的了解客户应用系统的主机的一些基本信息,我们可以通过Linux的命令获得相关信息,自己信息总结,我这里收集总结了基于Python2.7的一些脚本,可以快速获得系统的基础...
  • linux里一切皆为文件,在linux/unix的根目录下,有个/proc目录,这个/proc 是一种内核和内核模块用来向进程(process)发送信息的机制(所以叫做“/proc”),这个伪文件系统允许与内核内部数据结构交互,获取有关...
  • 最近想持续监服务器的测硬盘容量,但是又不想在服务器上东搞西搞,发现python有个paramiko可以连接linux, # -*- coding: utf-8 -*-# @Author : mlp# @File : linux_email.pyimport paramiko,re,time,smtplibimport ...
  • python监控linux磁盘空间使用情况

    千次阅读 2018-03-20 17:20:38
    # -*- coding: UTF-8 -*-'''@author: zhanglw'''from email.header import Headerfrom email.mime.text import MIMETextfrom email.utils import parseaddr, formataddrfrom email.mime.multipart import MIMEMultip...
  • 两种方法,获取磁盘剩余空间--PYTHON

    千次阅读 2019-05-28 04:15:24
    import ctypes import os import platform import sys def get_free_space_mb(folder): """ Return folder/drive free space (in bytes) """ if platform.system() == 'Windo...
  • linux里一切皆为文件,在linux/unix的根目录下,有个/proc目录,这个/proc 是一种内核和内核模块用来向进程(process)发送信息的机制(所以叫做“/proc”),这个伪文件系统允许与内核内部数据结构交互,获取有关...
  • python 获得磁盘空间 statvfs

    千次阅读 2011-05-09 16:49:00
    这个df命令有个问题,即是磁盘的某个卷有问题,比如offline了 那么很有可能就是当你执行df命令的时候,就挂掉了,在开发一个系统中,需要随时获得指定磁盘的剩余空间的功能 (如果使用df,很有可能...
  • 试了个多平台通用的版本: import subprocess import os import re def sh(command, print_msg=True): p = subprocess.Popen( command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) ...
  • 文件大小与占用空间是不一样的,一般占用空间是真实大小的1.1-1.4倍吧; python中检测文件大小函数...在Linux中,使用shell结合正则表达式获取文件夹占用大小,示例代码如下:   __author__ = 'weiran' import...
  • Linux获取磁盘空间利用率方式

    千次阅读 2016-11-05 19:49:58
    Linux获取磁盘空间利用率方式  下面使用python语言来讲解如何获取磁盘空间利用率的问题。    1. os.statvfs(path) 方法用于返回包含文件描述符fd的文件的文件系统的信息,其中path表示文件路径。   ...
  • Python3.6 安装psutil 模块和功能简介

    千次阅读 2017-05-18 10:13:55
    1. psutil是一个跨平台库(http://code.google.com/p/psutil/),能够轻松实现获取系统运行的进程和系统利用率(包括CPU、内存、磁盘、网络等)信息。它主要应用于系统监控,分析和限制系统资源及进程的管理。它实现...
  • # 获取/目录的磁盘信息 info = os.statvfs('/') free_size = info.f_bsize * info.f_bavail / 1024 / 1024 print(f'可用磁盘空间:{free_size}MB') 与直接使用系统df命令查看到的结果一致 变量解读 f_bsize是当前...
  • 环境使用python3.6.2版本,linux使用centos7 这个程序主要使用paramiko模块实现。我们逐步实现相关功能。 1、内存信息读取。通过远程执行‘cat /proc/meminfo’可以获取内存相关信息。这里我只读取MemTotal和...
  • Python os.statvfs() 方法os.statvfs() 方法用于返回包含文件描述符fd的文件的文件系统的信息。 语法 statvfs()方法语法格式如下:os.statvfs([path]) 参数path -- 文件路径。 返回值返回的结构: f_bsize: 文件系统...
  • 详解Python3.7安装psutil

    千次阅读 2018-12-09 22:55:58
    psutil 是一个跨平台库,能够轻松实现获取系统运行的进程和系统利用率(包括CPU ,内存,磁盘,网络等)信息。它主要应用于系统监控,分析和限制系统资源及进程的管理。它实现了同等命令行工具提供的功能,如ps ,.....
  • 基于pythonLinux服务器资源监控

    千次阅读 2020-05-17 13:28:18
    监控Linux服务器的工具、组件和程序网上有很多,但是一台服务器上会有很多进程同时运行,特别是做性能测试的时候,可能一台服务器上部署多个服务,如果只监控整个服务器的CPU和内存,当某个服务出现性能问题时,并不...
1 2 3 4 5 ... 20
收藏数 32,169
精华内容 12,867
关键字:

python获取linux磁盘信息