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

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


下面的程序展示了如何指定非布尔类型的选项。该程序是对第6个程序的重写,附加了一个选项用于指定你感兴趣的网络设备。

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

def netdevs(iface=None):
  ''' 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 not iface:
      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))
    else:
      if line[0].strip() == iface:
        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__':

  parser = argparse.ArgumentParser(description='Network Interface Usage Monitor')
  parser.add_argument('-i','--interface', dest='iface',
            help='Network interface')

  args = parser.parse_args()

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

当你不带任何参数执行程序的时候,程序的行为与之前的版本完全一致。然后,你也可以指定感兴趣的网络设备。例如:

$ ./net_devs_2.py

em1: 0.0 MiB 0.0 MiB
wlan0: 146.099492073 MiB 12.9737148285 MiB
virbr1: 0.0 MiB 0.0 MiB
virbr1-nic: 0.0 MiB 0.0 MiB

$ ./net_devs_2.py --help
usage: net_devs_2.py [-h] [-i IFACE]

Network Interface Usage Monitor

optional arguments:
 -h, --help      show this help message and exit
 -i IFACE, --interface IFACE
            Network interface

$ ./net_devs_2.py -i wlan0
wlan0: 146.100307465 MiB 12.9777050018 MiB


脚本的系统范围可用性
在本文的帮助下,你可能已经可以写一个或多个有用的脚本,就像其它linux命令一样,你想要每天都使用它们。最简单的方式是将脚本设置为可执行的,然后为脚本设置一个BASH别名。你也可以移除.py扩展名,然后将脚本放在诸如/usr/local/sbin这样的标准位置。

其它有用的标准库模组
除了本文中已经提到的标准库模组,还有很多其它有用的标准模组:subprocess、ConfigParser、readline和curses。

接下来做什么?
在这个阶段,依靠你自己使用Python的经验,探索Linux内部,你可以参考下面的任一方式。如果你曾经需要写很多shell脚本/命令流水线来探索Linux内部,那么试一下Python。如果你想要一个更简单的方式来编写执行很多任务的实用程序脚本,那么试一下Python。最后,如果你已经使用Python在Linux上别写其它目的的程序,那么试一下用Python探索Linux内部。