Python之psutil模塊的使用


1、psutil模塊的作用:

psutil是一個開源且跨平台的庫,提供獲取操作的信息,如cpu、內存、磁盤、網絡等信息,psutil還提供了許多命令行工具提供的功能,
包括ps,top,lsof,netstat,ifconfig,who,df,kill,free,nice,ionice,iostat,uptim,pidof,tty,taskset,pmap。非常強大!

 2、psutil模塊的安裝

pip install psutil

 3、獲取CPU常用的信息

import psutil

# 獲取CPU常用的信息
print(psutil.cpu_count())  # 獲取邏輯的CPU個數
print(psutil.cpu_count(logical=False))  # 獲取物理的CPU個數
print(psutil.cpu_percent())  # 獲取CPU的利用率
print(psutil.cpu_percent(percpu=True))  # 獲取所有邏輯CPU個數的利用率
print(psutil.cpu_percent(percpu=True, interval=2))  # 獲取2秒內所有邏輯CPU個數的利用率
print(psutil.cpu_times(percpu=True))  # 查看所有CPU的時間花費
print(psutil.cpu_percent(percpu=True, interval=3))  # 查看3秒內所有CPU的時間花費的比例
print(psutil.cpu_stats())  # 查看CPU上下文切換,中斷,軟中斷,系統調用次數

 4、獲取內存常用的信息

import psutil

# 獲取內存常用的信息
print(psutil.virtual_memory())  # 查看總內存、可用內存,內存利用率,buffer和cached等,除了內存利用率,其它單位是字節

def byte2human(n):
    """
    字節自動轉為可讀性強的函數
    :param n:字節數
    :return:
    """
    symbols = ('K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y')
    prefix = {}
    for i, s in enumerate(symbols):
        prefix[s] = 1 << (i + 1) * 10  # 左位移2位乘10
    for s in reversed(symbols):
        if n >= prefix[s]:  # 只在大於1000的時候,才轉換為K
            value = float(n) / prefix[s]
            return '%.1f%s' % (value, s)
    return '%sB' % n
result = byte2human(psutil.virtual_memory().total)
print(result)

print(psutil.swap_memory()) #查看虛擬內存的使用情況

 5、獲取磁盤的常用信息

import psutil
print(psutil.disk_partitions()) #查看磁盤名稱、掛載點、文件系統的類型等信息

def get_disk_via_moutpoint(mountpoint):
    """查看硬盤掛載磁盤"""
    disk = [item for item in psutil.disk_partitions() if item.mountpoint == mountpoint]
    return disk[0].device
result = get_disk_via_moutpoint('C:\\')
print(result)

print(psutil.disk_usage('C:\\'))  # 查看硬盤的大小,已使用磁盤容量,空間利用率等
print(psutil.disk_io_counters(perdisk=True))  # 查看每個磁盤的讀的次數,寫的次數,讀字節數,寫的字節數等,省去了解析/pro/diskstats文件

 6、獲取網絡相關的信息

import psutil

# 獲取網絡相關的信息
print(psutil.net_io_counters()) #獲取所有網口的所有流量和包
print(psutil.net_io_counters(pernic=True)) #獲取每張網口的流量和包
print(psutil.net_connections())  # 獲取每個網絡連接的信息
print(psutil.net_if_addrs()) #獲取網卡的配置信息
print(psutil.net_if_stats())  # 獲取網卡是否啟動、通信類型,MTU,傳輸速度等

 7、其它參數的獲取

import psutil
import datetime

print(psutil.users()) # 獲取用戶登陸信息

print(psutil.boot_time()) #返回啟動系統的時間戳
t = datetime.datetime.fromtimestamp(psutil.boot_time()).strftime('%Y-%m-%d %H:%M:%S')
print(t)

8、進程管理常用方法

import psutil
import datetime
import signal

init_process = psutil.Process(11288)  # 獲取linux 第一個進程
print(init_process.cmdline())  # 獲取啟動的程序位置
print(init_process.name())  # 獲取進程名字
print(datetime.datetime.fromtimestamp(init_process.create_time()).strftime('%Y-%m-%d %H:%M:%S'))  # 獲取進程啟動時間
print(init_process.num_fds()) #獲取文件打開個數
print(init_process.threads()) #獲取子進程的個數
print(init_process.is_running())#判斷進程是否運行着
init_process.send_signal(signal.SIGKILL)#發送信號給進程
init_process.kill() #發送SIGKILL信號結束進程
init_process.terminate()  # 發送SIGTERM信號結束進程

print(psutil.pids()) #獲取正在運行的所在pid
print(psutil.pid_exists(1))  # 判斷pid是否存在

# 迭代獲取所有的進程對象
for item in psutil.process_iter():
    print(item)

9、獲取一台主機的監控信息且發送郵件的示例

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>監控信息</title>
</head>
<body>
<table border="1">
    <tr>
        <td>服務器名稱</td>
        <td>{{hostname}}</td>
    </tr>
    <tr>
        <td>開機時間</td>
        <td>{{boot_time}}</td>
    </tr>
    <tr>
        <td>CPU個數</td>
        <td>{{cpu_count}}</td>
    </tr>
    <tr>
        <td>CPU利用率</td>
        <td>{{cpu_percent}}</td>
    </tr>
    <tr>
        <td>內存總量</td>
        <td>{{mem_total}}</td>
    </tr>
    <tr>
        <td>內存利用率</td>
        <td>{{mem_percent}}</td>
    </tr>
    <tr>
        <td>內存已用空間</td>
        <td>{{mem_used}}</td>
    </tr>
    <tr>
        <td>內存可用空間</td>
        <td>{{mem_free}}</td>
    </tr>
    <tr>
        <td>磁盤空間總量</td>
        <td>{{disk_total}}</td>
    </tr>
    <tr>
        <td>磁盤空間利用率</td>
        <td>{{disk_percent}}</td>
    </tr>
    <tr>
        <td>磁盤已用空間</td>
        <td>{{disk_used}}</td>
    </tr>
    <tr>
        <td>磁盤可用空間</td>
        <td>{{disk_free}}</td>
    </tr>
</table>
</body>
</html>
index.html

 

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import datetime
import jinja2
import socket

import psutil
import os
import yamail

def render(tpl_path, *args, **kwargs):
    """渲染html模板"""
    path, filename = os.path.split(tpl_path)
    return jinja2.Environment(
        loader=jinja2.FileSystemLoader(path or './')
    ).get_template(filename).render(**kwargs)

def byte2human(n):
    """
    字節自動轉為可讀性強的函數
    :param n:字節數
    :return:
    """
    symbols = ('K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y')
    prefix = {}
    for i, s in enumerate(symbols):
        prefix[s] = 1 << (i + 1) * 10  # 左位移2位乘10
    for s in reversed(symbols):
        if n >= prefix[s]:  # 只在大於1000的時候,才轉換為K
            value = float(n) / prefix[s]
            return '%.1f%s' % (value, s)
    return '%sB' % n

def get_cpu_info():
    """獲取CPU個數和1秒內CPU的利用率"""
    cpu_count = psutil.cpu_count()
    cpu_percent = psutil.cpu_percent(interval=1)
    return dict(cpu_count=cpu_count, cpu_percent=cpu_percent)

def get_memory_info():
    """獲取內存的信息"""
    virtual_mem = psutil.virtual_memory()
    mem_total = byte2human(virtual_mem.total)  # 總內存大小
    mem_percent = virtual_mem.percent  # 內存的使用率

    mem_free = byte2human(virtual_mem.free)  # 未使用內存
    mem_used = byte2human(virtual_mem.total * (virtual_mem.percent / 100))  # 使用內存
    return dict(mem_total=mem_total, mem_percent=mem_percent, mem_free=mem_free, mem_used=mem_used)

def get_disk_info():
    """獲取硬盤的信息"""
    disk_usage = psutil.disk_usage('C:\\')
    disk_total = byte2human(disk_usage.total)  # 硬盤總大小
    disk_percent = disk_usage.percent  # 硬盤的使用率
    disk_free = byte2human(disk_usage.free)  # 硬盤未使用大小
    disk_used = byte2human(disk_usage.used)  # 硬盤的使用大小
    return dict(
        disk_total=disk_total,
        disk_percent=disk_percent,
        disk_free=disk_free,
        disk_used=disk_used
    )


def get_boot_info():
    """查看系統的開始時間"""
    boot_time = datetime.datetime.fromtimestamp(psutil.boot_time()).strftime('%Y-%m-%d %H:%M:%S')
    return dict(boot_time=boot_time)


def collect_monitor_data():
    """將所有字典組合成在一起"""
    data = {}
    data.update(get_boot_info())
    data.update(get_cpu_info())
    data.update(get_disk_info())
    data.update(get_memory_info())
    return data

if __name__ == '__main__':
    email_username = 'xxx@qq.com'
    email_password = 'xxxx'
    smtp_ip = 'smtp.ym.163.com'

    RECV_EMAIL = ['xxx@qq.com']

    hostname = socket.gethostname()
    data = collect_monitor_data()
    data.update(hostname=hostname)

    content = render('index.html', **data)

    with yamail.SMTP(email_username, email_password, host=smtp_ip, port=465) as yag:
        for to_email in RECV_EMAIL:
            yag.send(to_email, subject='監控信息', contents=content)

 測試效果

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM