Get an instance of operating system information using Python

  • 2020-05-10 18:24:51
  • OfStack

preface

Every operations staff should be a machine configuration on the management of their own is very clear, because it is of great help to quickly we deal with our problems, such as with business growth, suddenly some machine load increases, this time to troubleshoot the reason, besides from the application, structure analysis, the analysis of the current hardware performance should be indispensable 1 ring, today we are going to be no third party module, use python bring module and the operation of the system to provide the information to get the information we need, this script in addition to hardware, also grabbed the current system processes and function of network traffic, so the basic corresponding to the previous version of the functions psutil The content of the implementation, many don't say, directly paste code:


#!/usr/bin/env python
 
from collections import OrderedDict
from collections import namedtuple
import os
import glob
import re
 
def cpuinfo():
 
 cpuinfo=OrderedDict()
 procinfo=OrderedDict()
 
 nprocs = 0
 with open('/proc/cpuinfo') as f:
 for line in f:
  if not line.strip():
  
  cpuinfo['proc%s' % nprocs] = procinfo
  nprocs=nprocs+1
  
  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
 
def meminfo():
 
 meminfo=OrderedDict()
 
 with open('/proc/meminfo') as f:
 for line in f:
  meminfo[line.split(':')[0]] = line.split(':')[1].strip()
 return meminfo
 
 
def netdevs():
 
 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
 
def process_list():
 
 pids = []
 for subdir in os.listdir('/proc'):
 if subdir.isdigit():
  pids.append(subdir)
 
 return pids
 
 
dev_pattern = ['sd.*','xv*']
 
def size(device):
 nr_sectors = open(device+'/size').read().rstrip('\n')
 sect_size = open(device+'/queue/hw_sector_size').read().rstrip('\n')
 
 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__':
 cpuinfo = cpuinfo()
 for processor in cpuinfo.keys():
 print(cpuinfo[processor]['model name'])
 
 meminfo = meminfo()
 print('Total memory: {0}'.format(meminfo['MemTotal']))
 print('Free memory: {0}'.format(meminfo['MemFree']))
 
 netdevs = netdevs()
 for dev in netdevs.keys():
 print('{0}: {1} MiB {2} MiB'.format(dev, netdevs[dev].rx, netdevs[dev].tx))
 
 
 pids = process_list()
 print('Total number of running processes:: {0}'.format(len(pids)))
 
 
 detect_devs()

Here's the explanation of the script:

1, OrderedDict, this function can be generated ordered dictionary, everyone knows that in python dictionary is disordered, of course you can also according to kye To sort, but to use OrderedDict You can generate the ordered dictionary directly, and the order of the ordered dictionary only depends on the order in which you add it.

2, namedtuple, function is can give tuple index a name, 1 we access tuple, can only use the index to access, but if you define the name of the index, you can use the name of the definition to access, for the convenience of everyone to understand, let's take a:


>>> from collections import namedtuple
>>> data = namedtuple('data',['rx','tx'])
>>> d = data(123,456)
>>> print d
data(rx=123, tx=456)
>>> print d.rx
123

3. glob, in this line for device in glob.glob(‘/sys/block/*') Using this function, its main method is glob , which returns a list of all matched files.

4, re.compile(pattern).match(os.path.basename(device)) Pattern Object and then use Pattern Matches the text, gets the match result, returns true if the match succeeds, and returns None if the match fails.

conclusion

The above is to use python to obtain all the information of the operating system, using python to obtain is still very convenient and practical, I hope this article can have a definite help to everyone's study and work.


Related articles: