它可以直接执行主机命令,在linux中使用ipython演示:
In [1]: import subprocess
In [2]: ret=subprocess.getoutput("ls /tmp")
#每一行都有换行符 显示都是文件夹名字
In [3]: ret
Out[3]: 'anaconda.log\nhsperfdata_root\nifcfg.log\nks-script-L6Zwly\nmozilla_root0\npackaging.log\nprogram.log\npyright-8362-6yKjdjW1Yfl3\npyright-8362-y829sh27zzav\npython-languageserver-cancellation\nsensitive-info.log\nssh-0GlZyEhYeuwL\nssh-mbNtzLwILFdW\nssh-rsRPXzqgEr2L\nssh-zySu9xXGdKd2\nstorage.log\nsystemd-private-21ba8a7f9ce24ad1a63e72fddc8711a7-bolt.service-AHv7YV\nsystemd-private-21ba8a7f9ce24ad1a63e72fddc8711a7-chronyd.service-0ScuoV\nsystemd-private-21ba8a7f9ce24ad1a63e72fddc8711a7-colord.service-cXKNYe\nsystemd-private-21ba8a7f9ce24ad1a63e72fddc8711a7-cups.service-iiyiVv\nsystemd-private-21ba8a7f9ce24ad1a63e72fddc8711a7-fwupd.service-snTpJR\nsystemd-private-21ba8a7f9ce24ad1a63e72fddc8711a7-rtkit-daemon.service-nB4rOV\nsystemd-private-3be6c1d224834a2a912310dc313a0e0a-bolt.service-EJll1C\nsystemd-private-3be6c1d224834a2a912310dc313a0e0a-chronyd.service-KI6DF2\nsystemd-private-3be6c1d224834a2a912310dc313a0e0a-colord.service-MDJesN\nsystemd-private-3be6c1d224834a2a912310dc313a0e0a-cups.service-kfJJ5z\nsystemd-private-3be6c1d224834a2a912310dc313a0e0a-fprintd.service-3AUrLA\nsystemd-private-3be6c1d224834a2a912310dc313a0e0a-fwupd.service-773Kod\nsystemd-private-3be6c1d224834a2a912310dc313a0e0a-rtkit-daemon.service-93vJSI\nsystemd-private-3be6c1d224834a2a912310dc313a0e0a-systemd-hostnamed.service-wyc5S8\nsystemd-private-60daec5e209e485ea3cef94cab77c77e-bolt.service-eynD1y\nsystemd-private-60daec5e209e485ea3cef94cab77c77e-chronyd.service-L17iWX\nsystemd-private-60daec5e209e485ea3cef94cab77c77e-colord.service-OBBpLd\nsystemd-private-60daec5e209e485ea3cef94cab77c77e-cups.service-v5ULMZ\nsystemd-private-60daec5e209e485ea3cef94cab77c77e-fwupd.service-T6c7js\nsystemd-private-60daec5e209e485ea3cef94cab77c77e-rtkit-daemon.service-GD0Euh\nsystemd-private-60daec5e209e485ea3cef94cab77c77e-systemd-hostnamed.service-C4mduf\nsystemd-private-fb3516e637f8482886b03ab7118e1636-bolt.service-jm0drc\nsystemd-private-fb3516e637f8482886b03ab7118e1636-chronyd.service-8RXScs\nsystemd-private-fb3516e637f8482886b03ab7118e1636-colord.service-dM5sib\nsystemd-private-fb3516e637f8482886b03ab7118e1636-cups.service-4Qg0Sv\nsystemd-private-fb3516e637f8482886b03ab7118e1636-fwupd.service-Dc1vrQ\nsystemd-private-fb3516e637f8482886b03ab7118e1636-rtkit-daemon.service-nddfhJ\ntmpaddon\ntracker-extract-files.0\ntracker-extract-files.1000\nvmware-root_704-2990744159\nvmware-root_709-4248287236\nvmware-root_711-4256610694\nvmware-root_717-4281712138\nvmware-root_721-4290559889\nvmware-root_735-4257003928\nvmware-root_738-2999591909\nvmware-root_739-4248680507\nvmware-root_744-2957583465\nvmware-root_748-2966037996\nvscode-typescript0\nyum.log\nyum_save_tx.2023-03-30.20-11.JjtP5G.yumtx\nyum_save_tx.2023-03-30.20-16.zfcoTW.yumtx\nyum_save_tx.2023-03-30.20-21.CJWcAV.yumtx\nyum_save_tx.2023-03-30.20-23.NRmhWB.yumtx'
使用split处理数据
In [4]: ret.split('\n')
Out[4]:
['anaconda.log',
'hsperfdata_root',
'ifcfg.log',
'ks-script-L6Zwly',
'mozilla_root0',
'packaging.log',
'program.log',
'pyright-8362-6yKjdjW1Yfl3',
'pyright-8362-y829sh27zzav',
'python-languageserver-cancellation',
'sensitive-info.log',
'ssh-0GlZyEhYeuwL',
'ssh-mbNtzLwILFdW',
'ssh-rsRPXzqgEr2L',
'ssh-zySu9xXGdKd2',
'storage.log',
'systemd-private-21ba8a7f9ce24ad1a63e72fddc8711a7-bolt.service-AHv7YV',
'systemd-private-21ba8a7f9ce24ad1a63e72fddc8711a7-chronyd.service-0ScuoV',
'systemd-private-21ba8a7f9ce24ad1a63e72fddc8711a7-colord.service-cXKNYe',
'systemd-private-21ba8a7f9ce24ad1a63e72fddc8711a7-cups.service-iiyiVv',
'systemd-private-21ba8a7f9ce24ad1a63e72fddc8711a7-fwupd.service-snTpJR',
'systemd-private-21ba8a7f9ce24ad1a63e72fddc8711a7-rtkit-daemon.service-nB4rOV',
'systemd-private-3be6c1d224834a2a912310dc313a0e0a-bolt.service-EJll1C',
'systemd-private-3be6c1d224834a2a912310dc313a0e0a-chronyd.service-KI6DF2',
'systemd-private-3be6c1d224834a2a912310dc313a0e0a-colord.service-MDJesN',
'systemd-private-3be6c1d224834a2a912310dc313a0e0a-cups.service-kfJJ5z',
'systemd-private-3be6c1d224834a2a912310dc313a0e0a-fprintd.service-3AUrLA',
'systemd-private-3be6c1d224834a2a912310dc313a0e0a-fwupd.service-773Kod',
'systemd-private-3be6c1d224834a2a912310dc313a0e0a-rtkit-daemon.service-93vJSI',
'systemd-private-3be6c1d224834a2a912310dc313a0e0a-systemd-hostnamed.service-wyc5S8',
'systemd-private-60daec5e209e485ea3cef94cab77c77e-bolt.service-eynD1y',
'systemd-private-60daec5e209e485ea3cef94cab77c77e-chronyd.service-L17iWX',
'systemd-private-60daec5e209e485ea3cef94cab77c77e-colord.service-OBBpLd',
'systemd-private-60daec5e209e485ea3cef94cab77c77e-cups.service-v5ULMZ',
'systemd-private-60daec5e209e485ea3cef94cab77c77e-fwupd.service-T6c7js',
'systemd-private-60daec5e209e485ea3cef94cab77c77e-rtkit-daemon.service-GD0Euh',
'systemd-private-60daec5e209e485ea3cef94cab77c77e-systemd-hostnamed.service-C4mduf',
'systemd-private-fb3516e637f8482886b03ab7118e1636-bolt.service-jm0drc',
'systemd-private-fb3516e637f8482886b03ab7118e1636-chronyd.service-8RXScs',
'systemd-private-fb3516e637f8482886b03ab7118e1636-colord.service-dM5sib',
'systemd-private-fb3516e637f8482886b03ab7118e1636-cups.service-4Qg0Sv',
'systemd-private-fb3516e637f8482886b03ab7118e1636-fwupd.service-Dc1vrQ',
'systemd-private-fb3516e637f8482886b03ab7118e1636-rtkit-daemon.service-nddfhJ',
'tmpaddon',
'tracker-extract-files.0',
'tracker-extract-files.1000',
'vmware-root_704-2990744159',
'vmware-root_709-4248287236',
'vmware-root_711-4256610694',
'vmware-root_717-4281712138',
'vmware-root_721-4290559889',
'vmware-root_735-4257003928',
'vmware-root_738-2999591909',
'vmware-root_739-4248680507',
'vmware-root_744-2957583465',
'vmware-root_748-2966037996',
'vscode-typescript0',
'yum.log',
'yum_save_tx.2023-03-30.20-11.JjtP5G.yumtx',
'yum_save_tx.2023-03-30.20-16.zfcoTW.yumtx',
'yum_save_tx.2023-03-30.20-21.CJWcAV.yumtx',
'yum_save_tx.2023-03-30.20-23.NRmhWB.yumtx']
In [1]: import subprocess
#命令
In [2]: prod_info='dmidecode -q -t 1 2>/dev/null'
In [3]: ret=subprocess.getoutput(prod_info).splitlines()
In [4]: ret
Out[4]:
['System Information',
'\tManufacturer: VMware, Inc.',
'\tProduct Name: VMware Virtual Platform',
'\tVersion: None',
'\tSerial Number: VMware-56 4d 3f ba 57 f1 59 24-90 27 9e b9 0e 58 1c b7',
'\tUUID: ba3f4d56-f157-2459-9027-9eb90e581cb7',
'\tWake-up Type: Power Switch',
'\tSKU Number: Not Specified',
'\tFamily: Not Specified']
循环打印,便于处理:
In [5]: for line in ret:
...: print(line)
...:
System Information
Manufacturer: VMware, Inc.
Product Name: VMware Virtual Platform
Version: None
Serial Number: VMware-56 4d 3f ba 57 f1 59 24-90 27 9e b9 0e 58 1c b7
UUID: ba3f4d56-f157-2459-9027-9eb90e581cb7
Wake-up Type: Power Switch
SKU Number: Not Specified
Family: Not Specified
一般获取了服务器信息,需要对其进行处理,获取我们需要的信息,变成字典,便于我们再次获取。
In [12]: for s in ret:
...: s=s.strip()
...: if 'Manufacturer' in s:
...: k,v=s.split(':')
...: prod_dic[k.lower()]=v
...: elif 'Product Name' in s:
...: k,v=s.split(':')
...: prod_dic[k.lower()]=v
...: elif 'Serial Number'in s:
...: k,v=s.split(':')
...: prod_dic[k.lower()]=v
...:
...:
In [13]: print(prod_dic)
{'manufacturer': ' VMware, Inc.', 'product name': ' VMware Virtual Platform', 'serial number': ' VMware-56 4d 3f ba 57 f1 59 24-90 27 9e b9 0e 58 1c b7'}
获取信息主要是主机名 ,内核,操作系统,CPU。
import subprocess as sp
#主机名
cmd_machine_name='uname -n'
hostName=sp.getoutput(cmd_machine_name)
#内核
cmd_kernel='uname -r'
kernel=sp.getoutput(cmd_kernel)
#操作系统
cmd_os_version=' cat /etc/redhat-release'
os=sp.getoutput(cmd_os_version)
baseInfo={
'hostName':hostName,
'kernel':kernel,
'os':os.strip()
}
print(baseInfo)
控制台输出信息:
{'hostName': 'localhost.localdomain', 'kernel': '3.10.0-1160.71.1.el7.x86_64', 'os': 'CentOS Linux release 7.9.2009 (Core)'}
将主板信息和基本信息合并,打印:
import subprocess as sp
#主板信息
prodInfo={'manufacturer': ' VMware, Inc.', 'product name': ' VMware Virtual Platform', 'serial number': ' VMware-56 4d 3f ba 57 f1 59 24-90 27 9e b9 0e 58 1c b7'}
#主机名
cmd_machine_name='uname -n'
hostName=sp.getoutput(cmd_machine_name)
#内核
cmd_kernel='uname -r'
kernel=sp.getoutput(cmd_kernel)
#操作系统
cmd_os_version=' cat /etc/redhat-release'
os=sp.getoutput(cmd_os_version)
baseInfo={
'hostName':hostName,
'kernel':kernel,
'os':os.strip()
}
baseInfo.update(prodInfo)
print(baseInfo)
控制台输出:
{'hostName': 'localhost.localdomain', 'kernel': '3.10.0-1160.71.1.el7.x86_64', 'os': 'CentOS Linux release 7.9.2009 (Core)', 'manufacturer': ' VMware, Inc.', 'product name': ' VMware Virtual Platform', 'serial number': ' VMware-56 4d 3f ba 57 f1 59 24-90 27 9e b9 0e 58 1c b7'}
import subprocess as sp
#cpu type
cpu_type="grep 'model name' /proc/cpuinfo | uniq"
cmd_cpu_pyc="grep 'physical id' /proc/cpuinfo | sort -u | wc -l"
cmd_cpu_cores_each="grep 'cpu cores' /proc/cpuinfo |uniq"
cpuType=sp.getoutput(cpu_type).strip() .split(': ')[1]
cpuPyc=sp.getoutput(cmd_cpu_pyc)
cpuCores=sp.getoutput(cmd_cpu_cores_each).split(': ')[1]
cpuInfo={
'cpuType':cpuType,
'cpuPyc':int(cpuPyc),
'cpuCoresEach':int(cpuCores)
}
print(cpuInfo)
控制台输出:
{'cpuType': 'Intel(R) Core(TM) i5-6300U CPU @ 2.40GHz', 'cpuPyc': 1, 'cpuCoresEach': 1}
优化代码:
定义一个tools.py文件:
import subprocess
#获取主机执行命令后的数据
def exec_cmd(cmd):
return subprocess.getoutput(cmd)
首先来编写查看内存信息的cmd命令:
[root@localhost ~]# dmidecode -q -t 17 2>/dev/null
#由于太长这里截取一部分内容,剩下的内容大致相同,只有参数不同
Memory Device
Total Width: 32 bits
Data Width: 32 bits
Size: 1024 MB
Form Factor: DIMM
Set: None
Locator: RAM slot #0
Bank Locator: RAM slot #0
Type: DRAM
Type Detail: EDO
Speed: Unknown
Manufacturer: Not Specified
Serial Number: Not Specified
Asset Tag: Not Specified
Part Number: Not Specified
Rank: Unknown
Configured Memory Speed: Unknown
Memory Device
Total Width: Unknown
Data Width: Unknown
Size: No Module Installed
Form Factor: DIMM
Set: None
Locator: RAM slot #1
Bank Locator: RAM slot #1
Type: DRAM
Type Detail: Unknown
这里每个内存信息都是Memory Device开头,可以使用split把每个信息都分开,然后逐个存入。
from tools import exec_cmd
import os
'''
判断文件是否为空
'''
def file_is_empty(file):
return os.stat(file).st_size==0
#获取内存信息cmd命令
cmd='dmidecode -q -t 17'
#存储内存信息文件名
fileName='/root/python_code/mem.txt'
fileContent=exec_cmd(cmd)
#写入文件里
with open(fileName,'w') as f:
if(file_is_empty):
f.write(fileContent)
#需要将内存块信息存入列表,分割
#读取文件
with open(fileName,'r') as f:
if(file_is_empty):
memStr=f.read()
memLs=memStr.split('Memory Device')[1:]
memInfo_ls=[]
for mem in memLs:
single_slot={}
for line in mem.splitlines():
line=line.strip()
if(len(line.split(":"))==2):
k,v=line.split(":")
single_slot[k]=v
break
memInfo_ls.append(single_slot)
print(memInfo_ls)
由于输出信息过大,这里只存储一组信息就停止,查看控制台输出:
[{'Total Width': ' 32 bits', 'Data Width': ' 32 bits', 'Size': ' 1024 MB', 'Form Factor': ' DIMM', 'Set': ' None', 'Locator': ' RAM slot #0', 'Bank Locator': ' RAM slot #0', 'Type': ' DRAM', 'Type Detail': ' EDO', 'Speed': ' Unknown', 'Manufacturer': ' Not Specified', 'Serial Number': ' Not Specified', 'Asset Tag': ' Not Specified', 'Part Number': ' Not Specified', 'Rank': ' Unknown', 'Configured Memory Speed': ' Unknown'}]