Home  >  Article  >  Backend Development  >  How to monitor real-time data of remote host in Python

How to monitor real-time data of remote host in Python

WBOY
WBOYforward
2023-05-12 17:55:141581browse

1 Program Description Document

1.1 Server

This program is a server program based on the TCP protocol. It can receive instructions sent by the client and perform corresponding operations. Finally, the operation The results are returned to the client. The program runs on port 8888 of localhost (this machine).

Main functions and commands:

• Get CPU usage: command "cpu"

• Get memory usage: command "memory"

• Get network bandwidth information: command "network"

• Get the current logged-in user: command "user"

• Get system load: command "loadavg"

• Get the current time: command "time"

• Get the process list: command "process"

• Get system information: command "system"

• Get the network connection list: command "connection"

• Get GPU usage: command "gpu"

• Get disk usage: command "disk"

For different instructions, the program uses different library functions for data acquisition and processing, as follows:

• For the instruction "cpu", use the psutil library to obtain the CPU usage.

• For the instruction "memory", use the psutil library to get the memory usage.

• For the command "network", use the speedtest-cli library to obtain network bandwidth information.

• For the instruction "user", use the psutil library to obtain the current logged in user.

• For the instruction "loadavg", use the os library to obtain the system load status.

• For the instruction "time", use the datetime library to get the current time.

• For the directive "process", use the psutil library to get the process list. The program sorts the processes according to memory usage and only returns the top 10 processes.

• For the instruction "system", use the platform library to obtain system information.

• For the command "connection", use the psutil library to obtain the network connection list. The program sorts the connections by process ID and only returns the first 10 connections.

• For the instruction "gpu", use the nvidia-smi tool to get the GPU usage.

• For the command "disk", use the psutil library to obtain disk usage.

The processing result of each instruction is returned to the client in the form of a string. When processing the instruction, the program determines whether the received data is empty. If empty, disconnect and close the client socket. The handle_client function in the program is a thread function responsible for communicating with a single client. Each client connection starts a thread.

1.2 Client

This program is a simple TCP client that can connect to a server and send requests to it, and then wait for the server's response. The program uses Python's socket module to create a TCP socket and connects to a server address using the connect method. The program continuously waits for the user to enter the request data type through a loop, then encodes the request data type into UTF-8 format and sends it to the server using the sendall method. The program then waits for the server to respond, decodes the response data into UTF-8 format and prints it out. Finally, the program closes the client socket.

The main process of the program is as follows:

1. Import the socket module.

2. Create a TCP socket object.

3. Connect to the specified server address.

4. Loop waiting for the user to input the requested data type.

5. Encode the request data type into UTF-8 format and send it to the server.

6. Wait for the server to respond and receive response data.

7. Decode the response data into UTF-8 format and print it out.

8. Close the client socket.

This program can be used to communicate with servers that provide specific data types. Users can enter different request data types to obtain different types of data. The server will return appropriate data based on the request type. The operation of the program depends on the availability and response speed of the server. If the server fails to respond, the program will wait until the server responds or the program is interrupted.

2 Code

Server

import os
import socket
import subprocess
import threading
from datetime import datetime
from sys import platform

import psutil
from speedtest import Speedtest

# 创建TCP套接字
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# 绑定IP和端口
server_address = ('localhost', 8888)
server_socket.bind(server_address)

# 监听连接请求
server_socket.listen(5)


def handle_client(client_socket, client_address):
    while True:
        # 接收客户端发送的数据
        data = client_socket.recv(1024)

        # 如果接收到空数据,则断开连接
        if not data:
            client_socket.close()
            print(f"Connection with {client_address} closed")
            break

        # 处理接收到的数据
        request = data.decode('utf-8')
        if request == 'cpu':
            # 使用psutil库获取CPU使用率
            cpu_percent = psutil.cpu_percent(interval=1)
            response_data = f'CPU使用率:{cpu_percent}%'.encode('utf-8')
        elif request == 'memory':
            # 使用psutil库获取内存使用率
            memory_percent = psutil.virtual_memory().percent
            response_data = f'内存使用率:{memory_percent}%'.encode('utf-8')
        elif request == 'network':
            # 使用speedtest-cli库获取网络带宽信息
            st = Speedtest()
            download_speed = st.download()
            upload_speed = st.upload()
            response_data = f'下载速度:{download_speed / 1000000}Mbps,上传速度:{upload_speed / 1000000}Mbps'.encode('utf-8')
        elif request == 'user':
            # 使用psutil库获取当前登录用户
            username = psutil.users()[0].name
            response_data = f'当前登录用户:{username}'.encode('utf-8')
        elif request == 'loadavg':
            # 使用os库获取系统负载情况
            load_avg = os.getloadavg()
            response_data = f'系统负载情况:{load_avg}'.encode('utf-8')
        elif request == 'time':
            # 使用datetime库获取当前时间
            current_time = datetime.datetime.now()
            response_data = f'当前时间:{current_time}'.encode('utf-8')
        elif request == 'process':
            # 使用psutil库获取进程列表
            process_list = []
            for process in psutil.process_iter(['pid', 'name', 'memory_info']):
                try:
                    process_list.append((process.info['pid'], process.info['name'], process.info['memory_info'].rss))
                except (psutil.AccessDenied, psutil.NoSuchProcess):
                    pass
            process_list.sort(key=lambda x: x[2], reverse=True)
            response_data = ''
            for i, (pid, name, memory) in enumerate(process_list[:10]):
                response_data += f'{i + 1}. 进程名称:{name},进程ID:{pid},占用内存:{memory / 1024 / 1024:.2f}MB\n'
            response_data = response_data.encode('utf-8')
        elif request == 'system':
            # 使用platform库获取系统信息
            system_info = f'操作系统:{platform.system()} {platform.release()}\n处理器:{platform.processor()}\nPython版本:{platform.python_version()}'
            response_data = system_info.encode('utf-8')
        elif request == 'connection':
            # 使用psutil库获取网络连接列表
            conn_list = []
            for conn in psutil.net_connections():
                if conn.status == psutil.CONN_ESTABLISHED:
                    conn_list.append((conn.laddr.ip, conn.laddr.port, conn.raddr.ip, conn.raddr.port, conn.pid))
            conn_list.sort(key=lambda x: x[4])
            response_data = ''
            for i, (laddr_ip, laddr_port, raddr_ip, raddr_port, pid) in enumerate(conn_list[:10]):
                response_data += f'{i + 1}. 本地地址:{laddr_ip}:{laddr_port},远程地址:{raddr_ip}:{raddr_port},进程ID:{pid}\n'
            response_data = response_data.encode('utf-8')
        elif request == 'disk':
            # 使用psutil库获取磁盘使用情况
            disk_usage = psutil.disk_usage('/')
            disk_info = f'磁盘总容量:{disk_usage.total / 1024 / 1024 / 1024:.2f}GB,已用容量:{disk_usage.used / 1024 / 1024 / 1024:.2f}GB,可用容量:{disk_usage.free / 1024 / 1024 / 1024:.2f}GB'
            response_data = disk_info.encode('utf-8')
        elif request == 'load':
            # 使用psutil库获取系统负载
            load_avg = psutil.getloadavg()
            load_info = f'1分钟内平均负载:{load_avg[0]:.2f},5分钟内平均负载:{load_avg[1]:.2f},15分钟内平均负载:{load_avg[2]:.2f}'
            response_data = load_info.encode('utf-8')
        elif request == 'thread':
            # 使用psutil库获取进程线程数
            thread_info = f'当前进程线程数:{psutil.Process().num_threads()}'
            response_data = thread_info.encode('utf-8')
        else:
            response_data = b'Invalid request'

        # 发送响应数据
        client_socket.sendall(response_data)


# 接收多个客户端连接
while True:
    client_socket, client_address = server_socket.accept()
    print(f"New connection from {client_address}")
    # 创建新线程处理客户端连接
    client_thread = threading.Thread(target=handle_client, args=(client_socket, client_address))
    client_thread.start()

Client

import socket

# 创建TCP套接字
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# 连接服务器
server_address = ('localhost', 8888)
client_socket.connect(server_address)

while True:
    # 发送请求数据给服务器
    request = input("请输入要请求的数据类型(cpu/memory/network/user/loadavg/time/process/system/connection/disk/load/thread):")
    client_socket.sendall(request.encode('utf-8'))

    # 接收服务器响应数据
    response_data = client_socket.recv(1024)

    # 处理接收到的数据
    response = response_data.decode('utf-8')
    print(response)

# 关闭客户端套接字
client_socket.close()

The above is the detailed content of How to monitor real-time data of remote host in Python. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete