使用 Python 获取 Linux 系统信息的代码

2019-10-06 11:29:02王振洲

#!/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__':

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

上面的程序当执行后会显示和下面类似的输出:

Total number of running processes:: 229

每个进程目录包含了一些其他文件和目录,如进程命令的调用,它正使用的共享库以及其它的。

每个进程目录包含了一些其他文件和目录,如进程命令的调用,它正使用的共享库以及其它的。

块设备

下一个程序通过读sysfs虚拟文件系统列出所有块设备。你系统中的块设备可以从/sys/block目录中找到。因此可能会有/sys/block/sda、/sys/block/sdb等这样的目录。为了获取所有这些设备,我们使用正则表达式对/sys/block目录进行扫描提取感兴趣的块设备。

#!/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()

如果你运行该程序,你将会看到下述类似的输出:


Device:: /sys/block/sda, Size:: 465.761741638 GiB 
Device:: /sys/block/mmcblk0, Size:: 3.70703125 GiB

当我运行该程序的时候,有个SD内存卡插在电脑上,因此你会看到程序检测到了它。你也可以扩展该程序识别其它块设备(比如虚拟硬盘)。

建立命令行实用工具
linux中命令行使用工具是无所不在的[@Lesus 注:曾有人说过:linux没有了命令行就是个渣。],它允许人么指定命令行参数来定制程序的默认行为。argparse模块就提供了和linux命令行实用工具类似的接口。下面的代码展示了程序如何获得系统上的所有用户以及打印它们的登录shell(使用了pwd标准库模块):

#!/usr/bin/env python

"""
Print all the users and their login shells
"""

from __future__ import print_function
import pwd


# Get the users from /etc/passwd
def getusers():
  users = pwd.getpwall()
  for user in users:
    print('{0}:{1}'.format(user.pw_name, user.pw_shell))

if __name__=='__main__':
  getusers()