# client_monitor.py
import socket
import threading
import subprocess
import time
import json
import psutil
import logging
from datetime import datetime, timedelta
import os
class LinuxSystemMonitor:
def __init__(self, host='0.0.0.0', port=8888):
self.host = host
self.port = port
self.is_running = True
self.realtime_monitoring = False
self.log_dir = "/var/log/system_monitor"
self.setup_logging()
def setup_logging(self):
"""设置日志系统"""
if not os.path.exists(self.log_dir):
os.makedirs(self.log_dir)
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s',
handlers=[
logging.FileHandler(f"{self.log_dir}/monitor.log"),
logging.StreamHandler()
]
)
self.logger = logging.getLogger(__name__)
def get_system_performance(self):
"""获取系统性能数据"""
try:
# CPU使用率
cpu_percent = psutil.cpu_percent(interval=1)
cpu_count = psutil.cpu_count()
# 内存使用情况
memory = psutil.virtual_memory()
memory_info = {
'total': memory.total,
'available': memory.available,
'percent': memory.percent,
'used': memory.used
}
# 磁盘IO
disk_io = psutil.disk_io_counters()
disk_info = {
'read_bytes': disk_io.read_bytes if disk_io else 0,
'write_bytes': disk_io.write_bytes if disk_io else 0,
'read_count': disk_io.read_count if disk_io else 0,
'write_count': disk_io.write_count if disk_io else 0
}
# 网络使用情况
net_io = psutil.net_io_counters()
network_info = {
'bytes_sent': net_io.bytes_sent,
'bytes_recv': net_io.bytes_recv,
'packets_sent': net_io.packets_sent,
'packets_recv': net_io.packets_recv
}
# 磁盘使用率
disk_usage = {}
for partition in psutil.disk_partitions():
try:
usage = psutil.disk_usage(partition.mountpoint)
disk_usage[partition.mountpoint] = {
'total': usage.total,
'used': usage.used,
'free': usage.free,
'percent': usage.percent
}
except PermissionError:
continue
# 系统负载
load_avg = os.getloadavg() if hasattr(os, 'getloadavg') else (0, 0, 0)
return {
'timestamp': datetime.now().isoformat(),
'cpu': {
'percent': cpu_percent,
'count': cpu_count
},
'memory': memory_info,
'disk_io': disk_info,
'network': network_info,
'disk_usage': disk_usage,
'load_avg': load_avg,
'boot_time': psutil.boot_time()
}
except Exception as e:
self.logger.error(f"获取系统性能数据失败: {e}")
return {}
def execute_system_command(self, command):
"""执行系统命令"""
try:
result = subprocess.run(
command,
shell=True,
capture_output=True,
text=True,
timeout=30
)
return {
'returncode': result.returncode,
'stdout': result.stdout,
'stderr': result.stderr
}
except subprocess.TimeoutExpired:
return {'error': '命令执行超时'}
except Exception as e:
return {'error': str(e)}
def save_performance_log(self, data):
"""保存性能日志到文件"""
try:
date_str = datetime.now().strftime('%Y-%m-%d')
log_file = f"{self.log_dir}/performance_{date_str}.log"
with open(log_file, 'a') as f:
f.write(json.dumps(data) + '\n')
except Exception as e:
self.logger.error(f"保存日志失败: {e}")
def handle_client_connection(self, client_socket, address):
"""处理客户端连接"""
self.logger.info(f"新的连接来自: {address}")
try:
while True:
# 接收数据
data = client_socket.recv(1024).decode('utf-8')
if not data:
break
try:
command = json.loads(data)
self.logger.info(f"接收到指令: {command}")
response = self.process_command(command)
client_socket.send(json.dumps(response).encode('utf-8'))
except json.JSONDecodeError:
error_response = {
'status': 'ERROR',
'message': '无效的JSON格式'
}
client_socket.send(json.dumps(error_response).encode('utf-8'))
except Exception as e:
self.logger.error(f"处理连接时出错: {e}")
finally:
client_socket.close()
self.logger.info(f"连接关闭: {address}")
def process_command(self, command):
"""处理指令"""
cmd_type = command.get('type', '')
if cmd_type == 'GET_HISTORY':
return self.get_history_logs(command.get('data', {}))
elif cmd_type == 'REALTIME_START':
self.realtime_monitoring = True
return {'status': 'SUCCESS', 'message': '实时监控已启动'}
elif cmd_type == 'REALTIME_STOP':
self.realtime_monitoring = False
return {'status': 'SUCCESS', 'message': '实时监控已停止'}
elif cmd_type == 'SYSTEM_INFO':
return {
'status': 'SUCCESS',
'data': self.get_system_performance()
}
else:
return {'status': 'ERROR', 'message': '未知指令'}
def get_history_logs(self, params):
"""获取历史日志"""
try:
days = params.get('days', 1)
log_files = []
for i in range(days):
date_str = (datetime.now() - timedelta(days=i)).strftime('%Y-%m-%d')
log_file = f"{self.log_dir}/performance_{date_str}.log"
if os.path.exists(log_file):
log_files.append(log_file)
return {'status': 'SUCCESS', 'log_files': log_files}
except Exception as e:
return {'status': 'ERROR', 'message': str(e)}
def start_realtime_monitoring(self, client_socket):
"""启动实时监控"""
while self.realtime_monitoring:
try:
system_info = self.get_system_performance()
if system_info:
data = {
'type': 'REALTIME_DATA',
'data': system_info,
'timestamp': time.time()
}
client_socket.send(json.dumps(data).encode('utf-8'))
time.sleep(5) # 5秒间隔
except Exception as e:
self.logger.error(f"实时监控错误: {e}")
break
def start_server(self):
"""启动服务器"""
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
try:
server_socket.bind((self.host, self.port))
server_socket.listen(5)
self.logger.info(f"监控客户端启动在 {self.host}:{self.port}")
# 启动性能监控线程
monitor_thread = threading.Thread(target=self.performance_monitor_worker)
monitor_thread.daemon = True
monitor_thread.start()
while self.is_running:
try:
client_socket, address = server_socket.accept()
client_thread = threading.Thread(
target=self.handle_client_connection,
args=(client_socket, address)
)
client_thread.daemon = True
client_thread.start()
except Exception as e:
self.logger.error(f"接受连接时出错: {e}")
except Exception as e:
self.logger.error(f"启动服务器失败: {e}")
finally:
server_socket.close()
def performance_monitor_worker(self):
"""性能监控工作线程"""
while self.is_running:
try:
system_info = self.get_system_performance()
if system_info:
self.save_performance_log(system_info)
time.sleep(300) # 5分钟记录一次
except Exception as e:
self.logger.error(f"性能监控错误: {e}")
time.sleep(60)
def main():
monitor = LinuxSystemMonitor()
try:
monitor.start_server()
except KeyboardInterrupt:
monitor.is_running = False
print("监控客户端已停止")
if __name__ == "__main__":
main()以上为client_monitor.py的具体代码,该如何修正使得能获取系统性能,生成完整的代码