python获取ubuntu系统信息

这个没啥说的,根据代码自取所需。

#!/usr/bin/env python
#coding:utf-8
import psutil
import datetime
import time

# 当前时间
now_time = time.strftime('%Y-%m-%d-%H:%M:%S', time.localtime(time.time()))
print(now_time)

# 查看cpu物理个数的信息
print(u"物理CPU个数: %s" % psutil.cpu_count(logical=False))

#CPU的使用率
cpu = (str(psutil.cpu_percent(1))) + '%'
print(u"cup使用率: %s" % cpu)

#查看内存信息,剩余内存.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().free) / float(psutil.virtual_memory().total)
print(u"物理内存: %s G" % total)
print(u"剩余物理内存: %s G" % free)
print(u"物理内存使用率: %s %%" % int(memory * 100))
# 系统启动时间
print(u"系统启动时间: %s" % datetime.datetime.fromtimestamp(psutil.boot_time()).strftime("%Y-%m-%d %H:%M:%S"))

# 系统用户
users_count = len(psutil.users())
#
# >>> for u in psutil.users():
# ...   print(u)
# ...
# suser(name='root', terminal='pts/0', host='61.135.18.162', started=1505483904.0)
# suser(name='root', terminal='pts/5', host='61.135.18.162', started=1505469056.0)
# >>> u.name
# 'root'
# >>> u.terminal
# 'pts/5'
# >>> u.host
# '61.135.18.162'
# >>> u.started
# 1505469056.0
# >>>

users_list = ",".join([u.name for u in psutil.users()])
print(u"当前有%s个用户,分别是 %s" % (users_count, users_list))
def getNet():
    sent_before = psutil.net_io_counters().bytes_sent  # 已发送的流量
    recv_before = psutil.net_io_counters().bytes_recv  # 已接收的流量
    time.sleep(1)
    sent_now = psutil.net_io_counters().bytes_sent
    recv_now = psutil.net_io_counters().bytes_recv
    sent = (sent_now - sent_before)/1024  # 算出1秒后的差值
    recv = (recv_now - recv_before)/1024
    print(time.strftime(" [%Y-%m-%d %H:%M:%S] ", time.localtime()))
    print("上传:{0}KB/s".format("%.2f"%sent))
    print("下载:{0}KB/s".format("%.2f"%recv))
def get_card_bytes_info():
    # bytes_sent
    try:
        card_ip = []
        card_io = []
        interface = []
        for k, v in psutil.net_if_addrs().items():
            if k not in 'lo':
                card_ip.append({'name': k, 'ip': v[0].address})

        for k, v in psutil.net_io_counters(pernic=True).items():
            if k not in 'lo':
                card_io.append({'name': k, 'out': v.bytes_sent, 'in': v.bytes_recv})

        for i in range(len(card_ip)):
            card = {
                'intName': card_io[i]['name'],
                'ip': card_ip[i]['ip'],
                'out': card_io[i]['out'],
                'in': card_io[i]['in']
            }
            interface.append(card)
        return interface
    except AttributeError as e:
        print("Please use psutil version 3.0 or above")
#网卡,可以得到网卡属性,连接数,当前流量等信息
net = psutil.net_io_counters()
bytes_sent = '{0:.2f} Mb'.format(net.bytes_recv / 1024 / 1024)
bytes_rcvd = '{0:.2f} Mb'.format(net.bytes_sent / 1024 / 1024)
print(u"网卡接收流量 %s 网卡发送流量 %s" % (bytes_rcvd, bytes_sent))
getNet()
print(get_card_bytes_info())
# io = psutil.disk_partitions()
# print(io)
# print("io[-1]为",io[-1])
#del io[-1]

print('-----------------------------磁盘信息---------------------------------------')
diskuse = psutil.disk_usage('/')
print("总容量:" + str(int(diskuse[0] / (1024.0 * 1024.0 * 1024.0))) + "G")
print("已用容量:" + str(int(diskuse[1] / (1024.0 * 1024.0 * 1024.0))) + "G")
print("可用容量:" + str(int(diskuse[2] / (1024.0 * 1024.0 * 1024.0))) + "G")
print("利用率:" + str(diskuse[3]))
# print("系统磁盘信息:" + str(io))
#
# for i in io:
#     o = psutil.disk_usage(i.device)
#     print("总容量:" + str(int(o.total / (1024.0 * 1024.0 * 1024.0))) + "G")
#     print("已用容量:" + str(int(o.used / (1024.0 * 1024.0 * 1024.0))) + "G")
#     print("可用容量:" + str(int(o.free / (1024.0 * 1024.0 * 1024.0))) + "G")

print('-----------------------------进程信息-------------------------------------')
# 查看系统全部进程
for pnum in psutil.pids():
    p = psutil.Process(pnum)
    print(u"进程名 %-20s  内存利用率 %-18s 进程状态 %-10s 创建时间 %-10s " \
    % (p.name(), p.memory_percent(), p.status(), p.create_time()))

也有更底层的数据:

import os
import json
import socket
import psutil


class Host:
    _hostname = socket.getfqdn(socket.gethostname())

    @classmethod
    def get_local_addr(cls):
        addr = socket.gethostbyname(cls._hostname)
        return addr

    @classmethod
    def get_hostname(cls):
        return cls._hostname

    @classmethod
    def ping(cls):
        result = os.system("ping -c 1 -w 1 %s >/dev/null" % cls.get_local_addr())
        if result == 0:
            return 1
        else:
            return 0


class CPU:

    @classmethod
    def _get_cpu_load(cls):
        # get cpu 5 minutes load
        loadavg = "/proc/loadavg"
        with open(loadavg) as f:
            con = f.read().split()
            return con[1]

    @classmethod
    def _get_cpu_usage(cls):
        # Return a float representing the current system-wide CPU utilization as a percentage
        return psutil.cpu_percent(interval=0.1)

    @classmethod
    def get_cpu_info(cls):
        cpu = {
            "cpuUtil": cls._get_cpu_load(),
            "cpuUsed": cls._get_cpu_usage()
        }
        return cpu


class Memory:
    mem = psutil.virtual_memory()

    @classmethod
    def _get_mem_total(cls):
        return cls.mem.total

    @classmethod
    def _get_mem_used(cls):
        return cls.mem.used

    @classmethod
    def get_mem_info(cls):
        mem = {
            "memUsed": cls._get_mem_used(),
            "memTotal": cls._get_mem_total(),
        }
        return mem


class NetworkCard:

    @classmethod
    def get_card_bytes_info(cls):
        # bytes_sent
        try:
            card_ip = []
            card_io = []
            interface = []
            for k, v in psutil.net_if_addrs().items():
                if k not in 'lo':
                    card_ip.append({'name': k, 'ip': v[0].address})

            for k, v in psutil.net_io_counters(pernic=True).items():
                if k not in 'lo':
                    card_io.append({'name': k, 'out': v.bytes_sent, 'in': v.bytes_recv})

            for i in range(len(card_ip)):
                card = {
                    'intName': card_io[i]['name'],
                    'ip': card_ip[i]['ip'],
                    'out': card_io[i]['out'],
                    'in': card_io[i]['in']
                }
                interface.append(card)
            return interface
        except AttributeError as e:
            print("Please use psutil version 3.0 or above")


class Disk:

    @classmethod
    def get_disk_info(cls):
        disklt = []
        for disk, sdiskio in psutil.disk_io_counters(perdisk=True, nowrap=False).items():
            if disk.startswith(('sd', 'vd')):
                device = '/dev/{}'.format(disk)
                capacity = psutil.disk_usage(device)
                diskdt = {
                    "diskName": device,
                    "total": capacity.total,
                    "used": capacity.used,
                    "ws": sdiskio.write_merged_count,
                    "rs": sdiskio.read_merged_count,
                    "wiops": sdiskio.write_count,
                    "riops": sdiskio.read_count,
                    "rkb": sdiskio.read_bytes / 1024,
                    "wkb": sdiskio.write_bytes / 1024
                }
                disklt.append(diskdt)
        return disklt


class Summary:
    def __init__(self):
        self._hostid = 1
        self._groupid = 1
        self._hostname = Host.get_hostname()
        self._ip = Host.get_local_addr()
        self._ping = Host.ping()
        self._cpu = CPU.get_cpu_info()
        self._memory = Memory.get_mem_info()
        self._network = NetworkCard.get_card_bytes_info()
        self._disk = Disk.get_disk_info()

    def start_collecting(self):
        summary = {
            'hostid': self._hostid,
            'groupid': self._groupid,
            'hostname': self._hostname,
            'ip': self._ip,
            'ping': self._ping,
            'cpu': self._cpu,
            'memory': self._memory,
            'network': self._network,
            'disk': self._disk
        }
        return json.dumps(summary)


if __name__ == '__main__':
    c = Summary()
    print(c.start_collecting())

猜你喜欢

转载自blog.csdn.net/qq_21454973/article/details/124478585