1. 程式人生 > >python3 獲取Linux系統信息

python3 獲取Linux系統信息

www cpu信息 os.path mage mib bytes pri 文件 def

系統信息

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‘])

技術分享

內存信息

文件/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/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

python3 獲取Linux系統信息