初学python不久,尝试使用python写一些简单脚本
1.简易版
shell居多
import os
_total_memory = "free -h | awk -F ' ' 'NR==2{print $2}'"
_use_memory = "free -h | awk -F ' ' 'NR==2{print $NF}'"
_disk_size = "fdisk -l | grep '磁盘 /dev/' | awk -F ',' '{print $1}'"
_cpu_core = "cat /proc/cpuinfo | grep 'cpu cores' | uniq"
_cpu_use = "top -n 1 | awk -F ',' 'NR==3{print $1}'"
print("总内存:")
_max_mem = os.system(_total_memory)
print("可用内存:")
_use_mem = os.system(_use_memory)
print("磁盘使用信息:")
_disk = os.system(_disk_size)
print("cpu核心")
_c_core = os.system(_cpu_core)
print("cpu使用率")
_c_use = os.system(_cpu_use)
演示
[root@Test02 ~]# ./test.py
总内存:
3.7G
已使用内存:
2.9G
磁盘使用信息:
磁盘 /dev/sda:107.4 GB
磁盘 /dev/mapper/centos-root:53.7 GB
磁盘 /dev/mapper/centos-swap:4160 MB
磁盘 /dev/mapper/centos-home:48.4 GB
cpu核心
cpu cores : 4
cpu使用率
%Cpu(s): 0.0 us
2.不成熟版
需要先在命令行下载psutil模块
pip install psutil
import time
import psutil
# !/usr/bin/python3
# coding:utf-8
# 当前时间
def get_time1():
now_time = time.strftime('%Y-%m-%d-%H:%M:%S', time.localtime(time.time()))
print(now_time)
def get_cpu():
print('-----------------------------cpu信息---------------------------------------')
# 查看cpu物理个数的信息,加u防止中文字符乱码
print(u"CPU核心数: %s" % psutil.cpu_count(logical=False))
# 物理核心
psutil.cpu_count(logical=False)
# CPU的使用率
cpu = (str(psutil.cpu_percent(1))) + '%'
print(u"cpu使用率: %s" % cpu)
def get_memory():
# get ip
print('-----------------------------内存信息---------------------------------------')
# 查看内存信息,剩余内存.free 总共.total
# round()函数方法为返回浮点数x的四舍五入值。
free = str(round(psutil.virtual_memory().free /
(1024.0 * 1024.0 * 1024.0), 2))
total = str(round(psutil.virtual_memory().total /
(1024.0 * 1024.0 * 1024.0), 2))
memory = int(psutil.virtual_memory().total -
psutil.virtual_memory().available) / float(psutil.virtual_memory().total)
print(u"总内存: %s G" % total)
print(u"剩余内存: %s G" % free)
print(u"内存使用率: %s %%" % int(memory * 100))
def get_disk():
print('-----------------------------磁盘信息---------------------------------------')
disk = psutil.disk_usage('/')
# _total= str(round(disk.total / (1024.0 * 1024.0 * 1024.0), 2))
# format格式化输出,保留2位小数
_total = format(disk.total / 1024 / 1024 / 1024, ".2f")
_free = format(disk.free / 1024 / 1024 / 1024, ".2f")
print(u"总磁盘空间: %s G" % _total)
print(u"剩余磁盘空间: %s G" % _free)
#调用
if __name__ == '__main__':
get_time1()
get_cpu()
get_memory()
get_disk()
演示
[root@Test02 ~]# ./system.py
2022-09-19-18:06:38
-----------------------------磁盘信息---------------------------------------
总磁盘空间: 49.98 G
剩余磁盘空间: 46.56 G
-----------------------------内存信息---------------------------------------
总内存: 3.7 G
剩余内存: 1.3 G
内存使用率: 22 %
-----------------------------cpu信息---------------------------------------
CPU核心数: 4
cpu使用率: 1.0%