python实战简单应用
程序员文章站
2022-07-12 21:11:40
...
一、Shell 命令
获取 CPU 信息
转载自: https://blog.csdn.net/qq_21127151/article/details/82195126.
二、Python 代码
1 获取 CPU 信息
获取物理CPU型号
grep 'model name' /proc/cpuinfo | uniq
In [1]: import subprocess
In [2]: cmd_cpu_name = "grep 'model name' /proc/cpuinfo | uniq"
In [3]: subprocess.getoutput(cmd_cpu_name)
Out[3]: 'model name\t: Intel(R) Xeon(R) Platinum 8163 CPU @ 2.50GHz'
In [4]: cpu_name = subprocess.getoutput(cmd_cpu_name).split(": ")[1]
In [5]: cpu_name
Out[5]: 'Intel(R) Xeon(R) Platinum 8163 CPU @ 2.50GHz'
查看物理CPU颗数
grep 'physical id' /proc/cpuinfo | sort -u | wc -l
In [8]: cmd_cpu_pyc = "grep 'physical id' /proc/cpuinfo | sort -u | wc -l"
In [9]: subprocess.getoutput(cmd_cpu_pyc)
Out[9]: '1'
In [10]: cpu_pyc = subprocess.getoutput(cmd_cpu_pyc)
In [11]: cpu_pyc = int(cpu_pyc)
查看每颗物理 CPU 的核心数
grep 'cpu cores' /proc/cpuinfo | uniq # 每颗 CPU 的核心数,不是总核心数
In [13]: subprocess.getoutput("grep 'cpu cores' /proc/cpuinfo | uniq")
Out[13]: 'cpu cores\t: 1'
In [14]: cpu_cores_each = subprocess.getoutput("grep 'cpu cores' /proc/cpuinfo | uniq")
In [15]: cpu_cores_each = cpu_cores_each.split(": ")[1]
In [16]: cpu_cores_each = int(cpu_cores_each)
In [17]: cpu_cores_each
Out[17]: 1
2 获取 IP 地址信息
In [2]: from subprocess import getoutput
In [3]: ret = getoutput("ip a")
In [4]: ips = []
...: for line in ret.splitlines():
...: if 'inet ' in line and '127.0.0.1' not in line:
...: _,ip,*_,net_name = line.split()
...: ips.append([net_name, ip])
...:
In [7]: ips
Out[7]: [['ens33', '10.11.59.169/24'], ['ens37', '192.168.8.128/24']]
3 获取硬盘信息
In [8]: from subprocess import getoutput
In [9]: ret = getoutput("lsblk")
In [10]: print(ret)
NAME MAJ:MIN RM SIZE RO TYPE MOUNTPOINT
sda 8:0 0 30G 0 disk
├─sda1 8:1 0 1G 0 part /boot
└─sda2 8:2 0 29G 0 part
├─centos-root 253:0 0 27G 0 lvm /
└─centos-swap 253:1 0 2G 0 lvm [SWAP]
sdb 8:16 0 5G 0 disk
sr0 11:0 1 4.3G 0 rom
In [11]: disks = []
...: for line in ret.splitlines():
...: if 'disk' in line:
...: dev_name, *_, size, _, _ = line.split()
...: disks.append([dev_name, size])
...:
In [12]: disks
Out[12]: [['sda', '30G'], ['sdb', '5G']]
上一篇: 【python简单应用】猜拳