Use Python to obtain operating system information instances and python instances
Preface
Every O & M personnel should be clear about the machine configuration they manage, because it is very helpful for us to quickly solve the problem. For example, as the business grows, the load of some machines suddenly increases sharply, in this case, in addition to analyzing applications and architectures, the current hardware performance analysis should be an essential part. Today we will not use third-party modules, use the python module and the running information provided by the system to obtain the required information. In addition to hardware, this script also captures the number of processes and network card Traffic functions of the current system, so the functions implemented in this version basically correspond to the previouspsutilThe implementation content is not mentioned. Directly paste the Code:
#!/usr/bin/env python from collections import OrderedDictfrom collections import namedtupleimport osimport globimport 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()
The following is an explanation of the script:
1. OrderedDictThis function can generate an ordered dictionary. Everyone knows that the dictionary is unordered in python.kyeTo sort, but useOrderedDictYou can directly generate an ordered dictionary. The order of the ordered dictionary is only related to the order you add.
2. namedtupleThe function is to give a name for the index of the tuples. Generally, we can only access the tuples by using indexes. However, if the name is defined for the index, you can access it with the defined name. For your convenience, let's give a question:
>>> from collections import namedtuple>>> data = namedtuple('data',['rx','tx'])>>> d = data(123,456)>>> print ddata(rx=123, tx=456)>>> print d.rx123
3. glob, In this linefor device in glob.glob(‘/sys/block/*')The main method for using this function isglobReturns the list of all matched files.
4. re. compile (pattern). match (OS. path. basename (device )),This is to compile the regular expressionPatternObject, and then usePatternMatch text to obtain the matching result. If the matching is successful, true is returned. If the matching fails, None is returned.
Summary
The above shows how to use python to obtain all the information about the operating system. It is very convenient and practical to use python. I hope this article will help you in your learning and work.