去评论
dz插件网

Windows远程桌面连接清理工具

饾暦饾枎饾枒饾枏饾枂饾枅饾枑
2025/10/07 14:48:13
运行脚本后,您会看到类似以下的输出:

==================================================
Windows远程桌面连接清理工具
==================================================
==================================================
检查最近使用的远程桌面连接记录...
==================================================
找到记录: 104.236.176.123:3389
找到记录: 45.79.28.119:3389

总共找到 2 个最近连接记录

==================================================
检查所有服务器记录...
==================================================
找到服务器: 104.236.176.123
找到服务器: 45.79.28.119

总共找到 2 个服务器记录

==================================================
检查RDP配置文件...
==================================================
找到RDP配置文件: C:\Users\用户名\documents\Default.rdp
文件大小: 2432 字节

==================================================
检查结果汇总
==================================================
最近连接记录数量: 2
服务器记录数量: 2
RDP配置文件: 存在

总共找到 4 条远程桌面连接相关记录

示例记录格式:
最近连接记录示例: 104.236.176.123:3389
服务器记录示例: 104.236.176.123

  1. #!/usr/bin/env python3# -*- coding: utf-8 -*-"""Windows远程桌面连接清理工具功能:1. 检查当前保存的远程桌面连接记录2. 清理所有远程桌面连接历史记录"""import osimport subprocessimport sysfrom typing import List, Dict, Tupleclass RDPCleaner:    """Windows远程桌面连接清理工具"""        def __init__(self):        self.default_reg_path = r"HKEY_CURRENT_USER\Software\Microsoft\Terminal Server Client\Default"        self.servers_reg_path = r"HKEY_CURRENT_USER\Software\Microsoft\Terminal Server Client\Servers"        self.rdp_file_path = os.path.join(os.path.expanduser("~"), "documents", "Default.rdp")            def run_command(self, command: str) -> Tuple[int, str, str]:        """执行命令并返回结果"""        try:            # 使用cmd执行命令            result = subprocess.run(                f"cmd /c {command}",                shell=True,                capture_output=True,                text=True,                encoding='gbk',                errors='ignore'            )            return result.returncode, result.stdout, result.stderr        except Exception as e:            return -1, "", str(e)        def check_mru_records(self) -> List[str]:        """检查最近使用的远程桌面连接记录"""        print("=" * 50)        print("检查最近使用的远程桌面连接记录...")        print("=" * 50)                returncode, stdout, stderr = self.run_command(f'reg query "{self.default_reg_path}"')                if returncode != 0:            print("未找到最近连接记录或查询失败")            return []                records = []        lines = stdout.strip().split('\n')                for line in lines:            line = line.strip()            if line.startswith('MRU') and 'REG_SZ' in line:                # 解析记录,格式如:MRU0    REG_SZ    192.168.1.1:3389                parts = line.split('REG_SZ')                if len(parts) > 1:                    record = parts[1].strip()                    records.append(record)                    print(f"找到记录: {record}")                print(f"\n总共找到 {len(records)} 个最近连接记录")        return records        def check_server_records(self) -> List[str]:        """检查所有服务器记录"""        print("\n" + "=" * 50)        print("检查所有服务器记录...")        print("=" * 50)                returncode, stdout, stderr = self.run_command(f'reg query "{self.servers_reg_path}"')                if returncode != 0:            print("未找到服务器记录或查询失败")            return []                servers = []        lines = stdout.strip().split('\n')                for line in lines:            line = line.strip()            if line and not line.startswith('HKEY_') and ':' not in line:                # 解析服务器IP或主机名                server = line.split('\\')[-1]                servers.append(server)                print(f"找到服务器: {server}")                print(f"\n总共找到 {len(servers)} 个服务器记录")        return servers        def check_rdp_file(self) -> bool:        """检查RDP配置文件是否存在"""        print("\n" + "=" * 50)        print("检查RDP配置文件...")        print("=" * 50)                if os.path.exists(self.rdp_file_path):            file_size = os.path.getsize(self.rdp_file_path)            print(f"找到RDP配置文件: {self.rdp_file_path}")            print(f"文件大小: {file_size} 字节")            return True        else:            print("未找到RDP配置文件")            return False        def clean_mru_records(self) -> bool:        """清理最近使用的远程桌面连接记录"""        print("\n" + "=" * 50)        print("清理最近使用的远程桌面连接记录...")        print("=" * 50)                returncode, stdout, stderr = self.run_command(f'reg delete "{self.default_reg_path}" /va /f')                if returncode == 0:            print("成功清理最近连接记录")            return True        else:            print(f"清理最近连接记录失败: {stderr}")            return False        def clean_server_records(self) -> bool:        """清理所有服务器记录"""        print("\n" + "=" * 50)        print("清理所有服务器记录...")        print("=" * 50)                returncode, stdout, stderr = self.run_command(f'reg delete "{self.servers_reg_path}" /f')                if returncode == 0:            print("成功清理服务器记录")            return True        else:            print(f"清理服务器记录失败: {stderr}")            return False        def clean_rdp_file(self) -> bool:        """清理RDP配置文件"""        print("\n" + "=" * 50)        print("清理RDP配置文件...")        print("=" * 50)                if not os.path.exists(self.rdp_file_path):            print("RDP配置文件不存在,无需清理")            return True                try:            # 检查文件是否为隐藏文件            is_hidden = os.stat(self.rdp_file_path).st_file_attributes & 2  # FILE_ATTRIBUTE_HIDDEN                        if is_hidden:                # 删除隐藏文件                returncode, stdout, stderr = self.run_command(f'del /ah "{self.rdp_file_path}"')            else:                # 删除普通文件                os.remove(self.rdp_file_path)                returncode = 0                        if returncode == 0:                print("成功清理RDP配置文件")                return True            else:                print(f"清理RDP配置文件失败: {stderr}")                return False        except Exception as e:            print(f"清理RDP配置文件时出错: {str(e)}")            return False        def verify_cleanup(self) -> Dict[str, bool]:        """验证清理结果"""        print("\n" + "=" * 50)        print("验证清理结果...")        print("=" * 50)                results = {            'mru_cleaned': True,            'servers_cleaned': True,            'rdp_file_cleaned': True        }                # 验证MRU记录        returncode, stdout, stderr = self.run_command(f'reg query "{self.default_reg_path}"')        if returncode == 0:            lines = stdout.strip().split('\n')            for line in lines:                if line.strip().startswith('MRU'):                    results['mru_cleaned'] = False                    print("警告: 仍有MRU记录未清理干净")                    break                # 验证服务器记录        returncode, stdout, stderr = self.run_command(f'reg query "{self.servers_reg_path}"')        if returncode == 0:            results['servers_cleaned'] = False            print("警告: 仍有服务器记录未清理干净")                # 验证RDP文件        if os.path.exists(self.rdp_file_path):            results['rdp_file_cleaned'] = False            print("警告: RDP配置文件仍然存在")                # 显示验证结果        print("\n验证结果:")        print(f"- 最近连接记录: {'已清理' if results['mru_cleaned'] else '未完全清理'}")        print(f"- 服务器记录: {'已清理' if results['servers_cleaned'] else '未完全清理'}")        print(f"- RDP配置文件: {'已清理' if results['rdp_file_cleaned'] else '未完全清理'}")                return results        def run_check_only(self):        """仅执行检查操作"""        print("Windows远程桌面连接检查工具")        print("=" * 50)                mru_records = self.check_mru_records()        server_records = self.check_server_records()        rdp_exists = self.check_rdp_file()                print("\n" + "=" * 50)        print("检查结果汇总")        print("=" * 50)        print(f"最近连接记录数量: {len(mru_records)}")        print(f"服务器记录数量: {len(server_records)}")        print(f"RDP配置文件: {'存在' if rdp_exists else '不存在'}")                total_records = len(mru_records) + len(server_records)        print(f"\n总共找到 {total_records} 条远程桌面连接相关记录")        def run_clean_only(self):        """仅执行清理操作"""        print("Windows远程桌面连接清理工具")        print("=" * 50)                # 执行清理        mru_success = self.clean_mru_records()        servers_success = self.clean_server_records()        rdp_success = self.clean_rdp_file()                # 验证清理结果        results = self.verify_cleanup()                print("\n" + "=" * 50)        print("清理完成")        print("=" * 50)        print("建议重启电脑以确保所有相关缓存完全清除")        print("如需删除保存的登录凭据,请到控制面板 > 凭据管理器中手动删除")        def run_full_process(self):        """执行完整的检查和清理流程"""        print("Windows远程桌面连接清理工具")        print("=" * 50)                # 1. 检查现有记录        mru_records = self.check_mru_records()        server_records = self.check_server_records()        rdp_exists = self.check_rdp_file()                total_records = len(mru_records) + len(server_records)                print("\n" + "=" * 50)        print("检查结果汇总")        print("=" * 50)        print(f"最近连接记录数量: {len(mru_records)}")        print(f"服务器记录数量: {len(server_records)}")        print(f"RDP配置文件: {'存在' if rdp_exists else '不存在'}")        print(f"\n总共找到 {total_records} 条远程桌面连接相关记录")                # 2. 询问是否继续清理        if total_records > 0 or rdp_exists:            print("\n" + "=" * 50)            print("准备清理所有记录")            print("=" * 50)                        # 执行清理            mru_success = self.clean_mru_records()            servers_success = self.clean_server_records()            rdp_success = self.clean_rdp_file()                        # 验证清理结果            results = self.verify_cleanup()                        print("\n" + "=" * 50)            print("清理完成")            print("=" * 50)            print("建议重启电脑以确保所有相关缓存完全清除")            print("如需删除保存的登录凭据,请到控制面板 > 凭据管理器中手动删除")        else:            print("\n未找到需要清理的记录")def main():    """主函数"""    cleaner = RDPCleaner()        if len(sys.argv) > 1:        mode = sys.argv[1].lower()        if mode == "--check":            cleaner.run_check_only()        elif mode == "--clean":            cleaner.run_clean_only()        else:            print("用法:")            print("  python rdp_cleaner.py          # 检查并清理")            print("  python rdp_cleaner.py --check  # 仅检查")            print("  python rdp_cleaner.py --clean  # 仅清理")    else:        cleaner.run_full_process()if __name__ == "__main__":    main()