python3 获取Linux系统信息

系统信息

import platform
platform.uname()
platform.architecture()

 

CPU信息

/proc/cpuinfo文件包含了系统处理器单元的信息。

#!/usr/bin/env/ python

"""
/proc/cpuinfo as a Python dict
"""
from __future__ import print_function
from collections import OrderedDict
import pprint

def cpuinfo():
    """
    Return the information in /proc/cpuinfo
    as a dictionary in the following format:
    cpu_info['proc0']={...}
    cpu_info['proc1']={...}
    """

    cpuinfo=OrderedDict()
    procinfo=OrderedDict()

    nprocs = 0
    with open('/proc/cpuinfo') as f:
        for line in f:
            if not line.strip():
                # end of one processor
                cpuinfo['proc%s' % nprocs] = procinfo
                nprocs=nprocs+1
                # Reset
                procinfo=OrderedDict()
            else:
                if len(line.split(':')) == 2:
                    procinfo[line.split(':')[0].strip()] = line.split(':')[1].strip()
                else:
                    procinfo[line.split(':')[0].strip()] = ''
            
    return cpuinfo

if __name__=='__main__':
    cpuinfo = cpuinfo()
    print(cpuinfo)
    for processor in cpuinfo.keys():
        print(cpuinfo[processor]['model name'])

cpu使用率:/proc/stat
1、匹配文件中CPU0,计算cpu_total1=user+nice+system+idle+iowait+irq+softirq
2、计算cpu_used1=user+nice+system+irq+softirq
3、记录cpu_total1和cpu_used1,sleep 15秒
4、同样方法重新计算cpu_total2、cpu_used2
5、cpu0在15秒内的平均使用率:(cpu_used2- cpu_used1)/(cpu_total2 - cpu_total1)*100%
cpu负载:/proc/loadavg

 

cpu 核心数量: cat /proc/stat | grep cpu | sed 1d | wc -l
cpu 频率: cat /proc/cpuinfo | grep 'cpu MHz' | tail -n1 | awk -F':' '{print $2}'

 

 

内存信息

文件/proc/meminfo系统内存的信息

#!/usr/bin/env python

from __future__ import print_function
from collections import OrderedDict

def meminfo():
    """  
    Return the information in /proc/meminfo
    as a dictionary 
    """

    meminfo=OrderedDict()

    with open('/proc/meminfo') as f:
        for line in f:
            meminfo[line.split(':')[0]] = line.split(':')[1].strip()
    return meminfo

if __name__=='__main__':
    print(meminfo())
    meminfo = meminfo()
    print('Total memory: {0}'.format(meminfo['MemTotal']))
    print('Free memory: {0}'.format(meminfo['MemFree']))

/proc/meminfo
内存总量:MemTotal
内存使用量:MemTotal - MemFree
应用程序内存使用量:MemTotal - MemFree - Buffers - Cached
swap总量:SwapTotal
swap使用量:SwapTotal - SwapFree
private内存占用:所有/proc/进程ID/smaps文件的Private_Clean和Private_Dirty加起来
Virtual内存占用:所有/proc/进程ID/smaps文件的Size加起来
共享内存:/dev/shm目录下所有子文件大小

 

网络统计信息

/proc/net/dev文件

#!/usr/bin/env python
from __future__ import print_function
from collections import namedtuple

def netdevs():
    """ 
    RX and TX bytes for each of the network devices 
    """

    with open('/proc/net/dev') as f:
        net_dump = f.readlines()

    device_data={}
    data = namedtuple('data',['rx','tx'])
    for line in net_dump[2:]:
        line = line.split(':')
        if line[0].strip() != 'lo':
            device_data[line[0].strip()] = data(float(line[1].split()[0])/(1024.0*1024.0),
                                                float(line[1].split()[8])/(1024.0*1024.0))
   
    return device_data

if __name__=='__main__':
    print(netdevs())
    netdevs = netdevs()
    for dev in netdevs.keys():
        print('{0}: {1} MiB {2} MiB'.format(dev, netdevs[dev].rx, netdevs[dev].tx)) 

 

进程信息

/proc目录包含了所有正运行的进程目录。这些目录的名字和进程的标识符是一样的。所以,如果你遍历/proc目录下那些使用数字作为它们的名字的目录,你就会获得所有现在正在运行的进程列表。

#!/usr/bin/env python
"""
List of all process IDs currently active
"""

from __future__ import print_function
import os
def process_list():

    pids = []
    for subdir in os.listdir('/proc'):
        if subdir.isdigit():
            pids.append(subdir)

    return pids


if __name__=='__main__':
    print(process_list())
    pids = process_list()
    print('Total number of running processes:: {0}'.format(len(pids)))

 

块设备

系统中的块设备可以从/sys/block目录中找到。因此可能会有/sys/block/sda、/sys/block/sdb等这样的目录。

#!/usr/bin/env python

"""
Read block device data from sysfs
"""

from __future__ import print_function
import glob
import re
import os

# Add any other device pattern to read from
dev_pattern = ['sd.*','mmcblk*']

def size(device):
    nr_sectors = open(device+'/size').read().rstrip('\n')
    sect_size = open(device+'/queue/hw_sector_size').read().rstrip('\n')

    # The sect_size is in bytes, so we convert it to GiB and then send it back
    return (float(nr_sectors)*float(sect_size))/(1024.0*1024.0*1024.0)

def detect_devs():
    for device in glob.glob('/sys/block/*'):
        for pattern in dev_pattern:
            if re.compile(pattern).match(os.path.basename(device)):
                print('Device:: {0}, Size:: {1} GiB'.format(device, size(device)))

if __name__=='__main__':
    detect_devs()

 

参考:http://www.oschina.net/translate/linux-system-mining-with-python

 

磁盘IO读:/proc/vmstat,pgpgin

磁盘IO写:/proc/vmstat,pgpgout

 

Linux 查看系统硬件信息一些命令

https://www.cnblogs.com/ggjucheng/archive/2013/01/14/2859613.html

 

posted @ 2017-06-30 14:19  shhnwangjian  阅读(3383)  评论(0编辑  收藏  举报