python后台监控脚本(记录实时进程,端口,键盘输入,录屏)

服务器中毒查询的好帮手,自动运行在后台,自动生成相关记录,前台不会有任何异常,可录屏,记录键盘等。

import psutil
import time
import logging
import requests
from pynput import keyboard
from threading import Thread
import cv2
import numpy as np
import mss

# ===== 日志配置 =====

# 进程日志
process_logger = logging.getLogger('process_logger')
process_logger.setLevel(logging.INFO)
process_handler = logging.FileHandler('process_monitor.log', encoding='utf-8')
process_formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
process_handler.setFormatter(process_formatter)
process_logger.addHandler(process_handler)

# 网络连接日志
connection_logger = logging.getLogger('connection_logger')
connection_logger.setLevel(logging.INFO)
connection_handler = logging.FileHandler('connection_monitor.log', encoding='utf-8')
connection_formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
connection_handler.setFormatter(connection_formatter)
connection_logger.addHandler(connection_handler)

# 键盘日志
keyboard_logger = logging.getLogger('keyboard_logger')
keyboard_logger.setLevel(logging.INFO)
keyboard_handler = logging.FileHandler('keyboard_monitor.log', encoding='utf-8')
keyboard_formatter = logging.Formatter('%(asctime)s - %(message)s')
keyboard_handler.setFormatter(keyboard_formatter)
keyboard_logger.addHandler(keyboard_handler)

# 屏幕录制日志
screen_logger = logging.getLogger('screen_logger')
screen_logger.setLevel(logging.INFO)
screen_handler = logging.FileHandler('screen_recording.log', encoding='utf-8')
screen_formatter = logging.Formatter('%(asctime)s - %(message)s')
screen_handler.setFormatter(screen_formatter)
screen_logger.addHandler(screen_handler)

# ===== 微信机器人配置 =====
WEBHOOK_URL = '自己填写自己申请的'


def send_wechat_message(message):
    """发送微信机器人消息"""
    payload = {
        "msgtype": "text",
        "text": {
            "content": message
        }
    }
    try:
        response = requests.post(WEBHOOK_URL, json=payload)
        return response.json()
    except Exception as e:
        process_logger.error(f"发送微信消息失败: {e}")


# ===== 进程监控模块 =====
def get_current_processes():
    return set(p.pid for p in psutil.process_iter(['pid']))


def monitor_processes(interval=1):
    previous_processes = get_current_processes()
    process_logger.info("进程监控开始...")

    while True:
        current_processes = get_current_processes()
        new_processes = current_processes - previous_processes

        if new_processes:
            process_logger.info(f"检测到新进程: {new_processes}")
            for pid in new_processes:
                try:
                    process = psutil.Process(pid)
                    process_name = process.name()
                    process_cmdline = ' '.join(process.cmdline())
                    process_exe = process.exe()
                    message = f"新进程详情: PID={pid}, 名称={process_name}, 命令行={process_cmdline}, 路径={process_exe}"
                    process_logger.info(message)
                    # send_wechat_message(message)  # 可选启用
                except psutil.NoSuchProcess:
                    process_logger.info(f"进程 {pid} 在检测时已终止")
                except psutil.AccessDenied:
                    process_logger.info(f"访问进程 {pid} 被拒绝")

        previous_processes = current_processes
        time.sleep(interval)


# ===== 网络连接监控模块 =====
def log_connections(interval=1):
    connection_logger.info("网络连接监控开始...")

    previous_tcp_connections = set()
    previous_udp_connections = set()

    while True:
        tcp_connections = psutil.net_connections(kind='tcp')
        udp_connections = psutil.net_connections(kind='udp')

        current_tcp_connections = set((conn.laddr, conn.raddr, conn.status) for conn in tcp_connections)
        current_udp_connections = set((conn.laddr, conn.raddr) for conn in udp_connections)

        new_tcp_connections = current_tcp_connections - previous_tcp_connections
        for conn in new_tcp_connections:
            laddr_ip, laddr_port = conn[0] if isinstance(conn[0], tuple) and len(conn[0]) == 2 else ("N/A", "N/A")
            raddr_ip, raddr_port = conn[1] if isinstance(conn[1], tuple) and len(conn[1]) == 2 else ("N/A", "N/A")
            status = conn[2]
            log_entry = f"TCP - 源IP: {laddr_ip} 源端口: {laddr_port} -> 目的IP: {raddr_ip} 目的端口: {raddr_port} 状态: {status}"
            connection_logger.info(log_entry)
            # send_wechat_message(log_entry)

        new_udp_connections = current_udp_connections - previous_udp_connections
        for conn in new_udp_connections:
            laddr_ip, laddr_port = conn[0] if isinstance(conn[0], tuple) and len(conn[0]) == 2 else ("N/A", "N/A")
            raddr_ip, raddr_port = conn[1] if isinstance(conn[1], tuple) and len(conn[1]) == 2 else ("N/A", "N/A")
            log_entry = f"UDP - 源IP: {laddr_ip} 源端口: {laddr_port} -> 目的IP: {raddr_ip} 目的端口: {raddr_port}"
            connection_logger.info(log_entry)
            # send_wechat_message(log_entry)

        previous_tcp_connections = current_tcp_connections
        previous_udp_connections = current_udp_connections
        time.sleep(interval)


# ===== 键盘监听模块 =====
def on_press(key):
    try:
        # 普通字符键(包括字母、数字、符号)
        if hasattr(key, 'char') and key.char is not None:
            keyboard_logger.info(f"Key pressed: {key.char}")
        else:
            # 特殊键(如 Shift、Ctrl、数字小键盘等)
            keyboard_logger.info(f"Special key pressed: {key}")
    except Exception as e:
        keyboard_logger.error(f"无法识别的按键: {key} - 错误: {e}")



def start_keyboard_listener():
    with keyboard.Listener(on_press=on_press) as listener:
        listener.join()




SCREEN_RECORDING_OUTPUT = 'screen_recording.avi'  # 改为 .avi 更兼容
SCREEN_RECORDING_FPS = 10.0
SCREEN_RECORDING_DURATION = None  # 设为整数秒数可限制录制时长


def start_screen_recording(duration=None):
    with mss.mss() as sct:
        monitor = sct.monitors[1]  # 主显示器
        width, height = monitor["width"], monitor["height"]

        # 使用 XVID 编码器和 AVI 格式,OpenCV 和大多数播放器都能识别
        fourcc = cv2.VideoWriter_fourcc(*'XVID')
        output_file = SCREEN_RECORDING_OUTPUT

        out = cv2.VideoWriter(output_file, fourcc, SCREEN_RECORDING_FPS, (width, height))

        screen_logger.info(f"开始屏幕录制: 分辨率={width}x{height}, 帧率={SCREEN_RECORDING_FPS}fps")

        start_time = time.time()
        frame_interval = 1.0 / SCREEN_RECORDING_FPS

        try:
            while True:
                if duration is not None and time.time() - start_time > duration:
                    screen_logger.info("屏幕录制达到设定时长,结束录制")
                    break

                img = sct.grab(monitor)
                frame = np.array(img)
                frame = cv2.cvtColor(frame, cv2.COLOR_BGRA2BGR)  # 转换为 BGR 格式
                out.write(frame)

                # 控制帧率
                time.sleep(max(0, frame_interval - (time.time() - start_time) % frame_interval))

        except Exception as e:
            screen_logger.error(f"屏幕录制过程中发生异常: {e}")
        finally:
            out.release()
            screen_logger.info("屏幕录制已停止")




# ===== 主函数启动线程 =====
def main():
    # 启动进程监控线程
    process_thread = Thread(target=monitor_processes, args=(1,), daemon=True)
    process_thread.start()

    # 启动网络连接监控线程
    connection_thread = Thread(target=log_connections, args=(1,), daemon=True)
    connection_thread.start()

    # 启动键盘监听线程
    keyboard_thread = Thread(target=start_keyboard_listener, daemon=True)
    keyboard_thread.start()

    # 启动屏幕录制线程(可选设定录制时长)
    screen_thread = Thread(target=start_screen_recording, args=(SCREEN_RECORDING_DURATION,), daemon=True)
    screen_thread.start()

    # 主线程保持运行
    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        process_logger.info("监控停止...")
        connection_logger.info("监控停止...")


if __name__ == "__main__":
    print("监控系统已启动...")
    main()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值