|
|
自用的todesk的隐私屏,分享给和我一样没开会员的兄弟们,水平有限,高人勿笑。
分享一个自用的todesk的隐私屏,给和我一样没开会员的兄弟们,没什么技术含量,高手勿笑~有AI真方便啊,有了ai少敲很多python代码,原理就是检测todesk进程和网络连接情况。
有一个bug,结束远控后需要晃动鼠标才能恢复显示,对于我的使用环境来说不影响,也懒的搞了~对付用用吧。
叠个甲:菜鸟自用的,没特别细的去研究它,可能有bug,高人自行修复哈,本人用着还好~~~
编译好的exe下载地址:
源码下载地址:
-----------------------------割-----------------------------------
可以直接下载advanced_screen_controller.exe,放入任务计划中,创建个基本任务,安全选项中选择“不管用户是否登录都要运行”以及“使用**高权限运行”;
触发器中选择在“启东时”运行,条件中取消“只有在计算机使用交流电源时才启动此任务”以及勾选“唤醒计算机运行此任务”就行了。
不放心的也可以自己编译exe,下载“for todesk.zip”,cd到它存放的目录下,用[size=0.875]pyinstaller --onefile --noconsole advanced_screen_controller.py。
记得安装pyinstaller。
-----------------------------割-----------------------------------
也可以下载for todesk.zip,解压到任意目录自行随意搞,当然要装python....
运行install.bat(仅一次),然后运行start_screen_controller.bat,
advanced_screen_controller.py就是代码了,高手们自己搞吧~
-----------------------------割-----------------------------------
当然,如果也懒的下载的话,就自行复制吧~ 哈哈哈哈哈哈。
[Python] 纯文本查看 复制代码# enhanced_todesk_monitor.py
import time
import ctypes
import psutil
import subprocess
import sys
import os
from datetime import datetime
def is_admin():
"""检查是否以管理员权限运行"""
try:
return ctypes.windll.shell32.IsUserAnAdmin()
except:
return False
def elevate_privileges():
"""请求以管理员权限重新运行脚本"""
if not is_admin():
print("请求管理员权限以执行底层显示设备操作...")
ctypes.windll.shell32.ShellExecuteW(None, "runas", sys.executable, " ".join(sys.argv), None, 1)
sys.exit(0)
class EnhancedToDeskMonitor:
def __init__(self, check_interval=3):
self.check_interval = check_interval
self.screen_off = False
self.running = True
# 状态跟踪
self.previous_stats = None
self.remote_start_time = None
self.last_recovery_attempt = 0
self.recovery_cooldown = 10 # 恢复尝试冷却时间(秒)
# 远程控制检测阈值
self.remote_threshold = {
'min_process_count': 3,
'min_upload_rate': 100,
'min_download_rate': 500,
'sustained_time': 5
}
# 退出黑屏的阈值
self.exit_threshold = {
'max_process_count': 2,
'max_upload_rate': 20,
'max_download_rate': 50,
'required_sustained_time': 8 # 需要持续8秒的低活动才退出黑屏
}
self.exit_start_time = None
def get_todesk_network_stats(self):
"""获取ToDesk进程的网络统计信息"""
try:
todesk_processes = []
total_upload = 0
total_download = 0
# 查找所有ToDesk相关进程
for proc in psutil.process_iter(['pid', 'name']):
if proc.info['name'] and 'todesk' in proc.info['name'].lower():
todesk_processes.append(proc.info['pid'])
try:
process = psutil.Process(proc.info['pid'])
io_counters = process.io_counters()
if io_counters:
total_upload += io_counters.write_bytes
total_download += io_counters.read_bytes
except (psutil.NoSuchProcess, psutil.AccessDenied):
continue
# 获取ToDesk相关网络连接
connections = psutil.net_connections()
todesk_connections = 0
todesk_ports = [35600, 443, 8081, 3478, 10999, 80, 5938]
for conn in connections:
if conn.status == 'ESTABLISHED' and conn.raddr:
# 检查端口和进程
if (conn.raddr.port in todesk_ports or
(hasattr(conn, 'pid') and conn.pid in todesk_processes)):
todesk_connections += 1
return {
'process_count': len(todesk_processes),
'total_upload': total_upload,
'total_download': total_download,
'total_connections': todesk_connections,
'timestamp': time.time()
}
except Exception as e:
print(f"获取网络统计时出错: {e}")
return {'process_count': 0, 'total_upload': 0, 'total_download': 0,
'total_connections': 0, 'timestamp': time.time()}
def calculate_traffic_rates(self, current_stats):
"""计算实时流量速率"""
if not self.previous_stats:
return 0, 0
time_diff = current_stats['timestamp'] - self.previous_stats['timestamp']
if time_diff == 0:
return 0, 0
upload_rate = (current_stats['total_upload'] - self.previous_stats['total_upload']) / time_diff
download_rate = (current_stats['total_download'] - self.previous_stats['total_download']) / time_diff
return upload_rate, download_rate
def robust_turn_on_screen(self):
"""
亮屏函数
"""
try:
print("执行增强型显示器恢复...")
success = False
# 方法1: 标准亮屏命令(主要方法)
result = ctypes.windll.user32.SendMessageW(0xFFFF, 0x112, 0xF170, -1)
if result == 0:
success = True
print(" ✅ 标准亮屏命令已发送")
time.sleep(0.5)
# 方法2: 模拟鼠标移动(辅助唤醒)
try:
# 获取当前鼠标位置
class POINT(ctypes.Structure):
_fields_ = [("x", ctypes.c_long), ("y", ctypes.c_long)]
pt = POINT()
if ctypes.windll.user32.GetCursorPos(ctypes.byref(pt)):
# 模拟小幅移动
ctypes.windll.user32.SetCursorPos(pt.x + 5, pt.y + 5)
time.sleep(0.1)
ctypes.windll.user32.SetCursorPos(pt.x, pt.y)
print(" ✅ 鼠标移动模拟完成")
except Exception as e:
print(f" 鼠标模拟失败: {e}")
# 方法3: 模拟按键事件
try:
ctypes.windll.user32.keybd_event(0x10, 0, 0, 0) # Shift按下
ctypes.windll.user32.keybd_event(0x10, 0, 2, 0) # Shift释放
ctypes.windll.user32.keybd_event(0x11, 0, 0, 0) # Ctrl按下
ctypes.windll.user32.keybd_event(0x11, 0, 2, 0) # Ctrl释放
print(" ✅ 按键模拟完成")
except Exception as e:
print(f" 按键模拟失败: {e}")
# 方法4: 防止系统休眠
try:
ctypes.windll.kernel32.SetThreadExecutionState(0x80000040)
print(" ✅ 线程执行状态已设置")
except Exception as e:
print(f" 设置执行状态失败: {e}")
# 方法5: 强制刷新显示驱动(需要管理员权限)
if is_admin() and not success:
success = self.force_refresh_display_driver()
return success
except Exception as e:
print(f"亮屏过程中出错: {e}")
return False
def force_refresh_display_driver(self):
"""强制刷新显示驱动程序(需要管理员权限)"""
try:
print(" 尝试强制刷新显示驱动...")
# 使用PowerShell禁用再启用显示适配器
refresh_script = """
$adapters = Get-PnpDevice | Where-Object {$_.Class -eq 'Display' -and $_.Status -eq 'OK'}
if ($adapters) {
foreach ($adapter in $adapters) {
Write-Host "重置显示适配器: $($adapter.FriendlyName)"
Disable-PnpDevice -InstanceId $adapter.InstanceId -Confirm false
Start-Sleep -Milliseconds 800
Enable-PnpDevice -InstanceId $adapter.InstanceId -Confirm false
Start-Sleep -Milliseconds 500
}
return $true
}
return $false
"""
result = subprocess.run(["powershell", "-Command", refresh_script],
capture_output=True, text=True, timeout=15)
if result.returncode == 0 and "True" in result.stdout:
print(" ✅ 显示驱动重置完成")
return True
except Exception as e:
print(f" 显示驱动重置失败: {e}")
return False
def turn_off_screen(self):
"""关闭显示器"""
try:
result = ctypes.windll.user32.SendMessageW(0xFFFF, 0x112, 0xF170, 2)
return result == 0
except Exception as e:
print(f"关闭显示器时出错: {e}")
return False
def analyze_remote_status(self, current_stats):
"""分析远程控制状态"""
if not self.previous_stats:
return False, "等待基准数据...", current_stats
upload_rate, download_rate = self.calculate_traffic_rates(current_stats)
process_count = current_stats['process_count']
connections = current_stats['total_connections']
print(f"[检测] 进程:{process_count} 连接:{connections} 上传:{upload_rate:.1f}B/s 下载:{download_rate:.1f}B/s")
# 判断条件
conditions_met = 0
if process_count >= self.remote_threshold['min_process_count']:
conditions_met += 1
if upload_rate >= self.remote_threshold['min_upload_rate']:
conditions_met += 1
if download_rate >= self.remote_threshold['min_download_rate']:
conditions_met += 1
is_remote = conditions_met >= 2
reason = f"满足{conditions_met}/3个条件"
if conditions_met > 0:
print(f" ✅ 远程条件: {reason}")
return is_remote, reason, current_stats
def should_exit_blackscreen(self, current_stats):
"""判断是否应该退出黑屏状态"""
if not self.screen_off or not self.previous_stats:
return False
upload_rate, download_rate = self.calculate_traffic_rates(current_stats)
process_count = current_stats['process_count']
current_time = time.time()
# 退出条件:严格的低活动检测
exit_conditions = (
process_count <= self.exit_threshold['max_process_count'] and
upload_rate <= self.exit_threshold['max_upload_rate'] and
download_rate <= self.exit_threshold['max_download_rate']
)
if exit_conditions:
if not self.exit_start_time:
self.exit_start_time = current_time
print(f"[退出检测] 开始计时...")
else:
duration = current_time - self.exit_start_time
if duration >= self.exit_threshold['required_sustained_time']:
print(f"[退出检测] 持续{duration:.1f}秒低活动,准备恢复显示器")
self.exit_start_time = None
return True
else:
self.exit_start_time = None
return False
def start_monitoring(self):
"""开始监控"""
print("=" * 70)
print("ToDesk远程黑屏守护程序")
print("=" * 70)
print("远控结束后被控端需要晃动鼠标恢复显示")
print("=" * 70)
try:
while self.running:
current_stats = self.get_todesk_network_stats()
current_time = time.time()
if self.screen_off:
# 黑屏状态:检查退出条件
if self.should_exit_blackscreen(current_stats):
# 防止频繁恢复尝试
if current_time - self.last_recovery_attempt >= self.recovery_cooldown:
print(f"[{datetime.now().strftime('%H:%M:%S')}] 🔄 尝试恢复显示器...")
if self.robust_turn_on_screen():
self.screen_off = False
self.last_recovery_attempt = current_time
print("✅ 显示器恢复成功")
else:
print("❌ 显示器恢复失败,将在冷却后重试")
self.last_recovery_attempt = current_time
else:
print("⏳ 恢复尝试冷却中...")
else:
# 保持监控但不重复触发
is_remote, reason, _ = self.analyze_remote_status(current_stats)
if is_remote:
print(f"🔒 黑屏保持中... {reason}")
else:
# 正常状态:检测远程控制
is_remote, reason, _ = self.analyze_remote_status(current_stats)
if is_remote:
if not self.remote_start_time:
self.remote_start_time = current_time
print(f"[{datetime.now().strftime('%H:%M:%S')}] 🚨 检测到远程控制: {reason}")
else:
duration = current_time - self.remote_start_time
if duration >= self.remote_threshold['sustained_time']:
print(f"[{datetime.now().strftime('%H:%M:%S')}] 🔥 确认远程控制,关闭显示器...")
if self.turn_off_screen():
self.screen_off = True
self.remote_start_time = None
self.exit_start_time = None
print("✅ 显示器已关闭")
else:
self.remote_start_time = None
self.exit_start_time = None
self.previous_stats = current_stats
time.sleep(self.check_interval)
except KeyboardInterrupt:
print("\n用户中断,正在退出...")
except Exception as e:
print(f"监控错误: {e}")
finally:
self.stop_monitoring()
def stop_monitoring(self):
"""安全停止监控"""
self.running = False
if self.screen_off:
print("**终恢复显示器...")
self.robust_turn_on_screen()
time.sleep(2)
print("程序安全退出")
def main():
"""主函数"""
# 提升权限
elevate_privileges()
print("ToDesk远程控制监控")
print("=" * 50)
print("✅ 管理员权限运行")
print("✅ 增强恢复功能已启用")
print()
# 创建监控实例
monitor = EnhancedToDeskMonitor(check_interval=2)
try:
monitor.start_monitoring()
except Exception as e:
print(f"程序运行出错: {e}")
monitor.stop_monitoring()
if __name__ == "__main__":
main()
免费评分
参与人数 3吾爱币 +3
热心值 +3
收起
理由
genius9609
+ 1
+ 1
我很赞同!
dogox
+ 1
+ 1
我很赞同!
AndyKuen
+ 1
+ 1
谢谢@Thanks!
查看全部评分 |
|