使用python写一个应用程序要求实现微软常用vc++功能排查与安装功能

news/2025/9/28 8:45:39/文章来源:https://www.cnblogs.com/spion/p/19116041
import os
import sys
import subprocess
import re
import requests
import tempfile
import platform
from bs4 import BeautifulSoup
import winregclass VCRedistManager:def __init__(self):self.supported_versions = {"2005": {"x86": "https://download.microsoft.com/download/8/B/4/8B42259F-5D70-43F4-AC2E-4B208FD8D66A/vcredist_x86.exe","x64": "https://download.microsoft.com/download/8/B/4/8B42259F-5D70-43F4-AC2E-4B208FD8D66A/vcredist_x64.exe"},"2008": {"x86": "https://download.microsoft.com/download/d/2/4/d242c3fb-da5a-4542-ad66-f9661d0a8d19/vcredist_x86.exe","x64": "https://download.microsoft.com/download/d/2/4/d242c3fb-da5a-4542-ad66-f9661d0a8d19/vcredist_x64.exe"},"2010": {"x86": "https://download.microsoft.com/download/1/6/5/165255E7-1014-4D0A-B094-B6A430A6BFFC/vcredist_x86.exe","x64": "https://download.microsoft.com/download/1/6/5/165255E7-1014-4D0A-B094-B6A430A6BFFC/vcredist_x64.exe"},"2013": {"x86": "https://download.microsoft.com/download/2/E/6/2E61CFA4-993B-4DD4-91DA-3737CD5CD6E3/vcredist_x86.exe","x64": "https://download.microsoft.com/download/2/E/6/2E61CFA4-993B-4DD4-91DA-3737CD5CD6E3/vcredist_x64.exe"},"2015-2022": {"x86": "https://aka.ms/vs/17/release/vc_redist.x86.exe","x64": "https://aka.ms/vs/17/release/vc_redist.x64.exe","arm64": "https://aka.ms/vs/17/release/vc_redist.arm64.exe"}}# 检查是否在Windows系统上运行if platform.system() != "Windows":print("错误: 此工具仅适用于Windows系统")sys.exit(1)# 检查是否以管理员权限运行self.is_admin = self.check_admin()if not self.is_admin:print("警告: 建议以管理员权限运行此程序以确保安装功能正常工作")def check_admin(self):"""检查程序是否以管理员权限运行"""try:return os.getuid() == 0except AttributeError:import ctypesreturn ctypes.windll.shell32.IsUserAnAdmin() != 0def get_installed_versions(self):"""获取系统中已安装的VC++版本"""installed = {}# 检查注册表中的已安装程序reg_paths = [r"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall",r"SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall"]for reg_path in reg_paths:try:key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, reg_path)i = 0while True:try:subkey_name = winreg.EnumKey(key, i)subkey = winreg.OpenKey(key, subkey_name)# 尝试获取显示名称try:display_name = winreg.QueryValueEx(subkey, "DisplayName")[0]# 检测VC++ redistributablevc_pattern = re.compile(r'Visual C\+\+ \d+ Redistributable(?: \(x86\)|\(x64\)|\(ARM64\))?')if vc_pattern.search(display_name):# 提取版本信息version_match = re.search(r'\d{4}', display_name)arch_match = re.search(r'(x86|x64|ARM64)', display_name)if version_match:version = version_match.group()# 特殊处理2015-2022版本if version == "2015" or version == "2017" or version == "2019" or version == "2022":version = "2015-2022"arch = arch_match.group().lower() if arch_match else "unknown"if version not in installed:installed[version] = set()installed[version].add(arch)except WindowsError:passwinreg.CloseKey(subkey)i += 1except WindowsError:breakwinreg.CloseKey(key)except WindowsError:pass# 转换集合为列表以便于处理for version in installed:installed[version] = list(installed[version])return installeddef display_installed_versions(self, installed_versions):"""显示已安装的VC++版本"""print("\n已安装的Microsoft Visual C++ Redistributable版本:")if not installed_versions:print("  未检测到已安装的VC++ Redistributable版本")returnfor version in sorted(installed_versions.keys()):arches = ", ".join(installed_versions[version])print(f"  {version} - 架构: {arches}")def check_missing_versions(self, installed_versions):"""检查缺失的VC++版本"""missing = {}for version, arches in self.supported_versions.items():if version not in installed_versions:# 整个版本都缺失missing[version] = list(arches.keys())else:# 检查该版本下缺失的架构installed_arches = installed_versions[version]for arch in arches.keys():if arch not in installed_arches:if version not in missing:missing[version] = []missing[version].append(arch)return missingdef display_missing_versions(self, missing_versions):"""显示缺失的VC++版本"""print("\n缺失的Microsoft Visual C++ Redistributable版本:")if not missing_versions:print("  没有检测到缺失的VC++ Redistributable版本")returnfor version in sorted(missing_versions.keys()):arches = ", ".join(missing_versions[version])print(f"  {version} - 架构: {arches}")def download_and_install(self, version, arch):"""下载并安装指定版本和架构的VC++ redistributable"""if version not in self.supported_versions or arch not in self.supported_versions[version]:print(f"错误: 不支持的VC++版本 {version} 或架构 {arch}")return Falseurl = self.supported_versions[version][arch]print(f"\n正在下载 {version} {arch} 版本...")try:# 创建临时文件with tempfile.NamedTemporaryFile(suffix=".exe", delete=False) as tmp_file:response = requests.get(url, stream=True)response.raise_for_status()# 下载文件total_size = int(response.headers.get('content-length', 0))downloaded_size = 0for chunk in response.iter_content(chunk_size=8192):if chunk:tmp_file.write(chunk)downloaded_size += len(chunk)progress = (downloaded_size / total_size) * 100 if total_size > 0 else 0print(f"下载进度: {progress:.1f}%", end='\r')installer_path = tmp_file.nameprint("\n下载完成,准备安装...")# 运行安装程序print(f"正在安装 {version} {arch} 版本...")subprocess.run([installer_path, "/quiet", "/norestart"], check=True)print(f"{version} {arch} 版本安装完成")# 清理临时文件try:os.unlink(installer_path)except:passreturn Trueexcept Exception as e:print(f"安装过程出错: {str(e)}")return Falsedef install_missing(self, missing_versions, select_all=False):"""安装缺失的VC++版本"""if not missing_versions:print("没有需要安装的缺失版本")returnfor version in sorted(missing_versions.keys()):arches = missing_versions[version]for arch in arches:if not select_all:response = input(f"是否安装 {version} {arch} 版本? (y/n): ")if response.lower() not in ['y', 'yes']:continueself.download_and_install(version, arch)def run(self):"""运行VC++ Redistributable管理工具"""print("="*50)print("Microsoft Visual C++ Redistributable 管理工具")print("="*50)while True:print("\n请选择操作:")print("1. 检查已安装的VC++版本")print("2. 检查并安装缺失的VC++版本")print("3. 安装所有支持的VC++版本")print("4. 退出")choice = input("请输入选项 (1-4): ")if choice == '1':installed = self.get_installed_versions()self.display_installed_versions(installed)elif choice == '2':installed = self.get_installed_versions()self.display_installed_versions(installed)missing = self.check_missing_versions(installed)self.display_missing_versions(missing)if missing:self.install_missing(missing)elif choice == '3':confirm = input("确定要安装所有支持的VC++版本吗? 这可能需要一些时间和磁盘空间。(y/n): ")if confirm.lower() in ['y', 'yes']:# 创建一个包含所有版本和架构的"缺失"字典all_versions = {v: list(a.keys()) for v, a in self.supported_versions.items()}self.install_missing(all_versions, select_all=True)elif choice == '4':print("感谢使用,再见!")breakelse:print("无效的选项,请重试")if __name__ == "__main__":try:manager = VCRedistManager()manager.run()except Exception as e:print(f"程序出错: {str(e)}")sys.exit(1)

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/920406.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

网站建设尺寸规范网络营销策划案的形式

给AWS新账户做完了对等连接,因为默认VPC网段都冲突 就换了VPC,然后发现新VPC内创建的实例都没有分配公网IP地址,自动分配公网IP地址变成了禁用。后续建机子需要手动修改成启用太麻烦了。 在VPC里面找到编辑子网设置,勾上启用自动…

网站建设全网营销客户资源心理咨询网站后台

传统蜂窝网络一般基于特定接入技术并针对大规模公共网络设计,无法灵活适配小规模网络以及异构无线技术。本文介绍了Magma在构建低成本异构无线接入方面的探索。原文: Building Flexible, Low-Cost Wireless Access Networks With Magma 摘要 当今仍然有数十亿人受限…

网站内容更新教程泰安网站开发公司

1.三次握手的概述 我们在学网络的概念时,每当讲到TCP都会听到三次握手和四次挥手,一直以来可能都对这个概念模糊不清,那么什么是三次握手和四次挥手呢?简单的举一个例子,如果我们和朋友打游戏,我们要和朋友…

广西壮族自治区住房和城乡建设厅网站手机网站开发源码

目录 一、什么是sql注入 二、sql语句的执行流程 三、内连接和外连接的区别 四、Union和Union All 有什么区别 五、MySql如何取差集 六、DELETE和TRUNCATE有什么区别 七、count(*)和count(1)的区别 八、MyISAM和InnoDB的区…

详细介绍:MySQL零基础学习Day4——多表查询

详细介绍:MySQL零基础学习Day4——多表查询pre { white-space: pre !important; word-wrap: normal !important; overflow-x: auto !important; display: block !important; font-family: "Consolas", &quo…

MetaGPT实战指南:构建模拟公司运营的多智能体系统 - 教程

MetaGPT实战指南:构建模拟公司运营的多智能体系统 - 教程pre { white-space: pre !important; word-wrap: normal !important; overflow-x: auto !important; display: block !important; font-family: "Consola…

2017网站建设报价单营销论坛网站建设

引言 在计算机科学中,数据结构和算法是构建高效软件系统的基石。而排序算法作为算法领域的重要组成部分,一直在各种应用场景中发挥着关键作用。今天我们将聚焦于一种基于插入排序的改进版本——希尔排序(Shell Sort),深…

Timeplus Enterprise 3.0 (Linux, macOS) - 流处理平台

Timeplus Enterprise 3.0 (Linux, macOS) - 流处理平台Timeplus Enterprise 3.0 (Linux, macOS) - 流处理平台 Revolutionize Streaming Analytics 请访问原文链接:https://sysin.org/blog/timeplus/ 查看最新版。原创…

《HelloGitHub》第 114 期

兴趣是最好的老师,HelloGitHub 让你对开源感兴趣!简介 HelloGitHub 分享 GitHub 上有趣、入门级的开源项目。github.com/521xueweihan/HelloGitHub这里有实战项目、入门教程、黑科技、开源书籍、大厂开源项目等,涵盖…

网站建设与准备乐清城市网官网

这阵子在捣鼓一个将游戏视频打包成本地可播放文件的模块。开始使用avi作为容器,弄了半天无奈avi对aac的支持实在有限,在播放时音视频时无法完美同步。 关于这点avi文档中有提到: For AAC, one RAW AAC frame usually spans over 1024 samples…

重庆网站推广网络推广申请建设部门网站的报告

大数据产业是以数据及数据所蕴含的信息价值为核心生产要素,通过数据技术、数据产品、数据服务等形式,使数据与信息价值在各行业经济活动中得到充分释放的赋能型产业。 大数据产业定义一般分为核心业态、关联业态、衍生业态三大业态。 一、专…

智能微电网 —— 如何无缝集成分布式光伏 / 风电? - 指南

pre { white-space: pre !important; word-wrap: normal !important; overflow-x: auto !important; display: block !important; font-family: "Consolas", "Monaco", "Courier New", …

【鸿蒙生态共建】一文说清基础类型数据的非预期输入转换与兜底-《精通HarmonyOS NEXT :鸿蒙App开发入门与项目化实战》读者福利 - 详解

【鸿蒙生态共建】一文说清基础类型数据的非预期输入转换与兜底-《精通HarmonyOS NEXT :鸿蒙App开发入门与项目化实战》读者福利 - 详解2025-09-28 08:16 tlnshuju 阅读(0) 评论(0) 收藏 举报pre { white-space: p…

一级a做爰片免费网站体验区网站制造

2014年杭州电子科技大学Java期末试卷.doc杭州电子科技大学学生考试卷( A )卷考试课程Java语言程序设计考试日期2014年 6月 16日成 绩课程号教师号任课教师姓名考生姓名学号(8位)年级专业注意:所有答案均写在答卷上,写在试卷上无效;(一)单选题(每题2分&am…

青岛商城网站建设劳务公司注册需要什么条件

CMA实验室认可,即中国计量认证(China Metrology Accreditation)的实验室资质认定,以下是对其的详细解读: 一、定义与目的 CMA认证是经省级以上人民政府计量行政部门对实验室的计量检定、测试能力和可靠性考核合格后进…

网站建设资质要求贝壳找房官网 二手房

文章目录 1 函数原型2 参数3 返回值4 使用说明5 示例5.1 示例1 1 函数原型 strcat():将src指向的字符串拼接在dest指向的字符串末尾,函数原型如下: char *strcat(char *dest, const char *src);2 参数 strcat()函数有两个参数src和dest&am…

网站建设需要条件查询网域名解析

共享数据缓冲区 概述共享数据缓冲区管理共享缓冲区管理的核心功能包括:共享数据缓冲区的组织结构初始化共享缓冲池BufferDesc 结构体InitBufferPool 函数如何确定请求的数据页面是否在缓冲区中?BufferTag 结构体RelFileNode 结构体ForkNumber 结构体ReadBuffer_common 函数怎…

Splunk Enterprise 10.0.1 (macOS, Linux, Windows) - 搜索、分析和可视化,数据全面洞察平台

Splunk Enterprise 10.0.1 (macOS, Linux, Windows) - 搜索、分析和可视化,数据全面洞察平台Splunk Enterprise 10.0.1 (macOS, Linux, Windows) - 搜索、分析和可视化,数据全面洞察平台 Search, analysis, and visu…

基于51单片机宠物喂食系统设计 - 指南

pre { white-space: pre !important; word-wrap: normal !important; overflow-x: auto !important; display: block !important; font-family: "Consolas", "Monaco", "Courier New", …