首页 > 其他分享 >自行搭建kms服务

自行搭建kms服务

时间:2023-09-05 17:33:12浏览次数:42  
标签:pkey set string Windows echo 自行 kms winversion% 搭建

一、使用Docker搭建KMS服务器

  • 安装docker

  Docker 教程 | 菜鸟教程 (runoob.com)

  • 拉取kms镜像文件
docker pull luodaoyi/kms-server
  • 运行镜像
docker run -itd -p 1688:1688 --name kms luodaoyi/kms-server
  • 搭建完毕

  把服务器IP内网DNS解析为kms.yourdomain.com,则kms服务地址:kms.yourdomain.com:1688

二、使用批处理写激活脚本

1. Windows激活脚本

@echo off
setlocal enabledelayedexpansion
title KMS激活工具

::::::::::::::::::::::::::::::::::run as admin::::::::::::::::::::::::::::::::::
::mode con lines=30 cols=60
::%1 mshta vbscript:createobject("shell.application").shellexecute("cmd.exe","/c %~s0 ::","","runas",1)(window.close)&&exit
::cd /d "%~dp0"
::请求管理员权限
%1 %2
mshta vbscript:createobject("shell.application").shellexecute("%~s0","goto :start","","runas",1)(window.close)&goto :eof
:::::::::::::::::::::::::::::::::::color echo:::::::::::::::::::::::::::::::::::
::https://stackoverflow.com/questions/4339649/how-to-have-multiple-colors-in-a-windows-batch-file
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
:color
for /F "tokens=1,2 delims=#" %%a in ('"prompt #$H#$E# & echo on & for %%b in (1) do rem"') do (
  set "DEL=%%a"
)
rem Prepare a file "X" with only one dot
<nul > X set /p ".=."
:: %1 颜色,%2~5输出内容
call :colorset %1 %2 %3 %4 %5
exit /b

:colorset
set "param=^%~2 %~3 %~4 %~5" !
set "param=!param:"=\"!"
findstr /p /A:%1 "." "!param!\..\X" nul
<nul set /p ".=%DEL%%DEL%%DEL%%DEL%%DEL%%DEL%%DEL%"
echo.
exit /b
:::::::::::::::::::::::start:::::::::::::::::::::::start:::::::::::::::::::::::
:start
cls
::!!!添加你自己的kms服务地址!!!
::set kmsserver=kms.yourdomain.com
set kmsserver=kms.yourdomain.com
if not defined kmsserver goto connectfail
echo 检查能否连接到公司KMS服务器……
::万能的ping >. <
ping -n 3 %kmsserver% > nul 2>&1
if %errorlevel% neq 0 (
    echo 公司KMS服务器连接失败,检查外部KMS服务器
    set kmsserver=kms.ghpym.com
    echo 检查能否连接到外部KMS服务器……
    ::万能的ping >. <
    ping -n 3 %kmsserver% > nul 2>&1 goto connectfail
)
echo.
call :color 0a 连接到KMS服务器成功
echo.
echo 检查系统激活状态
cscript //Nologo %windir%\system32\slmgr.vbs /xpr | find "批量激活" > nul && goto activewindowsdone 
cscript //Nologo %windir%\system32\slmgr.vbs /xpr | find "批量激活" > nul || goto getosver

:connectfail
cls
echo.
echo =====================================================
call :color 04 无法连接到服务器……
call :color 04 此脚本需要结合kms服务,请勿单独使用!!!
call :color 04 请确保已经正确配置kms服务,并设置变量 kmsserver !!!
echo =====================================================
echo.
pause
goto :eof

:: 获取系统版本
:: key https://docs.microsoft.com/en-us/windows-server/get-started/kmsclientkeys
:: for /f "tokens=3 delims= " %%i in ('reg QUERY "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion" /v "EditionID" ^| find "ProductName"') do set EditionID=%%i
:getosver
::注意,winversion=%%i %%j,%%j后面不要有空格
for /f "tokens=3*" %%i IN ('reg query "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion" /v ProductName ^| find "ProductName"') do set winversion=%%i %%j
echo %winversion% | find /I "Windows 7" && set osver=win7
echo %winversion% | find /I "Windows 8" && set osver=win8
echo %winversion% | find /I "Windows 8.1" && set osver=win8.1
echo %winversion% | find /I "Windows 10" && set osver=win10
echo %winversion% | find /I "Server 2008"  && set osver=2008
echo %winversion% | find /I "Server 2008 R2" && set osver=2008r2
echo %winversion% | find /I "Server 2012"  && set osver=2012
echo %winversion% | find /I "Server 2012 R2" && set osver=2012r2
echo %winversion% | find /I "Server 2016" && set osver=2016
echo %winversion% | find /I "Server 2019" && set osver=2019
::if DEFINED osver goto %osver%
if not defined winversion goto getosverfail
if defined osver (goto %osver%) else (goto getosverfail)

:getosverfail
cls
echo.
call :color 04 QAQ不支持的系统版本……
echo.
pause
goto :eof

:2008
if "%winversion%" == "Windows Web Server 2008" set pkey=WYR28-R7TFJ-3X2YQ-YCY4H-M249D
if "%winversion%" == "Windows Server 2008 Standard" set pkey=TM24T-X9RMF-VWXK6-X8JC9-BFGM2
if "%winversion%" == "Windows Server 2008 Standard without Hyper-V" set pkey=W7VD6-7JFBR-RX26B-YKQ3Y-6FFFJ
if "%winversion%" == "Windows Server 2008 Enterprise" set pkey=YQGMW-MPWTJ-34KDK-48M3W-X4Q6V
if "%winversion%" == "Windows Server 2008 Enterprise without Hyper-V" set pkey=39BXF-X8Q23-P2WWT-38T2F-G3FPG
if "%winversion%" == "Windows Server 2008 HPC" set pkey=RCTX3-KWVHP-BR6TB-RB6DM-6X7HP
if "%winversion%" == "Windows Server 2008 Datacenter" set pkey=7M67G-PC374-GR742-YH8V4-TCBY3
if "%winversion%" == "Windows Server 2008 Datacenter without Hyper-V" set pkey=22XQ2-VRXRG-P8D42-K34TD-G3QQC
if "%winversion%" == "Windows Server 2008 for Itanium-Based Systems" set pkey=4DWFP-JF3DJ-B7DTH-78FJB-PDRHK
goto activewindows

:2008r2
if "%winversion%" == "Windows Server 2008 R2 Web" set pkey=6TPJF-RBVHG-WBW2R-86QPH-6RTM4
if "%winversion%" == "Windows Server 2008 R2 HPC edition" set pkey=TT8MH-CG224-D3D7Q-498W2-9QCTX
if "%winversion%" == "Windows Server 2008 R2 Standard" set pkey=YC6KT-GKW9T-YTKYR-T4X34-R7VHC
if "%winversion%" == "Windows Server 2008 R2 Enterprise" set pkey=489J6-VHDMP-X63PK-3K798-CPX3Y
if "%winversion%" == "Windows Server 2008 R2 Datacenter" set pkey=74YFP-3QFB3-KQT8W-PMXWJ-7M648
if "%winversion%" == "Windows Server 2008 R2 for Itanium-based Systems" set pkey=GT63C-RJFQ3-4GMB6-BRFB9-CB83V
goto activewindows

:2012
if "%winversion%" == "Windows Server 2012" set pkey=BN3D2-R7TKB-3YPBD-8DRP2-27GG4
if "%winversion%" == "Windows Server 2012 N" set pkey=8N2M2-HWPGY-7PGT9-HGDD8-GVGGY
if "%winversion%" == "Windows Server 2012 Single Language" set pkey=2WN2H-YGCQR-KFX6K-CD6TF-84YXQ
if "%winversion%" == "Windows Server 2012 Country Specific" set pkey=4K36P-JN4VD-GDC6V-KDT89-DYFKP
if "%winversion%" == "Windows Server 2012 Server Standard" set pkey=XC9B7-NBPP2-83J2H-RHMBY-92BT4
if "%winversion%" == "Windows Server 2012 MultiPoint Standard" set pkey=HM7DN-YVMH3-46JC3-XYTG7-CYQJJ
if "%winversion%" == "Windows Server 2012 MultiPoint Premium" set pkey=XNH6W-2V9GX-RGJ4K-Y8X6F-QGJ2G
if "%winversion%" == "Windows Server 2012 Datacenter" set pkey=48HP8-DN98B-MYWDG-T2DCC-8W83P
goto activewindows

:2012r2
if "%winversion%" == "Windows Server 2012 R2 Server Standard" set pkey=D2N9P-3P6X9-2R39C-7RTCD-MDVJX
if "%winversion%" == "Windows Server 2012 R2 Datacenter" set pkey=W3GGN-FT8W3-Y4M27-J84CP-Q3VJ9
if "%winversion%" == "Windows Server 2012 R2 Essentials" set pkey=KNC87-3J2TX-XB4WP-VCPJV-M4FWM
goto activewindows

:2016
if "%winversion%" == "Windows Server 2016 Datacenter" set pkey=CB7KF-BWN84-R7R2Y-793K2-8XDDG
if "%winversion%" == "Windows Server 2016 Standard" set pkey=WC2BQ-8NRM3-FDDYY-2BFGV-KHKQY
if "%winversion%" == "Windows Server 2016 Essentials" set pkey=JCKRF-N37P4-C2D82-9YXRT-4M63B
goto activewindows

:2019
if "%winversion%" == "Windows Server 2019 Datacenter" set pkey=WMDGN-G9PQG-XVVXX-R3X43-63DFG
if "%winversion%" == "Windows Server 2019 Standard" set pkey=N69G4-B89J2-4G8F4-WWYCC-J464C
if "%winversion%" == "Windows Server 2019 Essentials" set pkey=WVDHN-86M7X-466P6-VHXV7-YY726
goto activewindows

::desktop
:win7
if "%winversion%" == "Windows 7 Professional" set pkey=FJ82H-XT6CR-J8D7P-XQJJ2-GPDD4
if "%winversion%" == "Windows 7 Professional N" set pkey=MRPKT-YTG23-K7D7T-X2JMM-QY7MG
if "%winversion%" == "Windows 7 Professional E" set pkey=W82YF-2Q76Y-63HXB-FGJG9-GF7QX
if "%winversion%" == "Windows 7 Enterprise" set pkey=33PXH-7Y6KF-2VJC9-XBBR8-HVTHH
if "%winversion%" == "Windows 7 Enterprise N" set pkey=YDRBP-3D83W-TY26F-D46B2-XCKRJ
if "%winversion%" == "Windows 7 Enterprise E" set pkey=C29WB-22CC8-VJ326-GHFJW-H9DH4
goto activewindows

:win8
if "%winversion%" == "Windows 8 Pro" set pkey=NG4HW-VH26C-733KW-K6F98-J8CK4
if "%winversion%" == "Windows 8 Pro N" set pkey=XCVCF-2NXM9-723PB-MHCB7-2RYQQ
if "%winversion%" == "Windows 8 Enterprise" set pkey=32JNW-9KQ84-P47T8-D8GGY-CWCK7
if "%winversion%" == "Windows 8 Enterprise N" set pkey=JMNMF-RHW7P-DMY6X-RF3DR-X2BQT
goto activewindows

:win8.1
if "%winversion%" == "Windows 8.1 Pro" set pkey=GCRJD-8NW9H-F2CDX-CCM8D-9D6T9
if "%winversion%" == "Windows 8.1 Pro N" set pkey=HMCNV-VVBFX-7HMBH-CTY9B-B4FXY
if "%winversion%" == "Windows 8.1 Enterprise" set pkey=MHF9N-XY6XB-WVXMC-BTDCT-MKKG7
if "%winversion%" == "Windows 8.1 Enterprise N" set pkey=TT4HM-HN7YT-62K67-RGRQJ-JFFXW
goto activewindows

:win10
if "%winversion%" == "Windows 10 Pro" set pkey=W269N-WFGWX-YVC9B-4J6C9-T83GX
if "%winversion%" == "Windows 10 Pro N" set pkey=MH37W-N47XK-V7XM9-C7227-GCQG9
if "%winversion%" == "Windows 10 Pro Workstations" set pkey=NRG8B-VKK3Q-CXVCJ-9G2XF-6Q84J
if "%winversion%" == "Windows 10 Pro Workstations N" set pkey=9FNHH-K3HBT-3W4TD-6383H-6XYWF
if "%winversion%" == "Windows 10 Pro Education" set pkey=6TP4R-GNPTD-KYYHQ-7B7DP-J447Y
if "%winversion%" == "Windows 10 Pro Education N" set pkey=YVWGF-BXNMC-HTQYQ-CPQ99-66QFC
if "%winversion%" == "Windows 10 Education" set pkey=NW6C2-QMPVW-D7KKK-3GKT6-VCFB2
if "%winversion%" == "Windows 10 Education N" set pkey=2WH4N-8QGBV-H22JP-CT43Q-MDWWJ
if "%winversion%" == "Windows 10 Enterprise" set pkey=NPPR9-FWDCX-D2C8J-H872K-2YT43
if "%winversion%" == "Windows 10 Enterprise N" set pkey=DPH2V-TTNVB-4X9Q3-TJR4H-KHJW4
if "%winversion%" == "Windows 10 Enterprise G" set pkey=YYVX9-NTFWV-6MDM3-9PT4T-4M68B
if "%winversion%" == "Windows 10 Enterprise G N" set pkey=44RPN-FTY23-9VTTB-MP9BX-T84FV
if "%winversion%" == "Windows 10 Enterprise LTSC 2019" set pkey=M7XTQ-FN8P6-TTKYV-9D4CC-J462D
if "%winversion%" == "Windows 10 Enterprise N LTSC 2019" set pkey=92NFX-8DJQP-P6BBQ-THF9C-7CG2H
if "%winversion%" == "Windows 10 Enterprise LTSB 2016" set pkey=DCPHK-NFMTC-H88MJ-PFHPY-QJ4BJ
if "%winversion%" == "Windows 10 Enterprise N LTSB 2016" set pkey=QFFDN-GRT3P-VKWWX-X7T3R-8B639
if "%winversion%" == "Windows 10 Enterprise 2015 LTSB" set pkey=WNMTR-4C88C-JK8YV-HQ7T2-76DF9
if "%winversion%" == "Windows 10 Enterprise 2015 LTSB N" set pkey=2F77B-TNFGY-69QQF-B8YKP-D69TJ
goto activewindows

:activewindows
echo.
echo 系统版本为: %winversion%
echo 对应的key:%pkey%
echo.
cscript //Nologo %windir%\system32\slmgr.vbs -ipk %pkey%
cscript //Nologo %windir%\system32\slmgr.vbs /skms %kmsserver%
cscript //Nologo %windir%\system32\slmgr.vbs /ato
cscript //Nologo %windir%\system32\slmgr.vbs /xpr | find "未激活" || find "通知模式" > nul && goto activewindowsfailed

:activewindowsdone
echo.
call :color 0a 系统激活成功
echo.
pause
goto :eof

:activewindowssuccess
echo.
call :color 0a 系统已经永久激活成功
echo.
pause
goto :eof

:activewindowsfailed
echo.
call :color 04 系统激活失败
echo.
pause
goto :eof

2. office激活脚本

@echo off
setlocal enabledelayedexpansion
title KMS激活工具

::::::::::::::::::::::::::::::::::run as admin::::::::::::::::::::::::::::::::::
::mode con lines=30 cols=60
::%1 mshta vbscript:createobject("shell.application").shellexecute("cmd.exe","/c %~s0 ::","","runas",1)(window.close)&&exit
::cd /d "%~dp0"
::请求管理员权限
%1 %2
mshta vbscript:createobject("shell.application").shellexecute("%~s0","goto :start","","runas",1)(window.close)&goto :eof
:::::::::::::::::::::::::::::::::::color echo:::::::::::::::::::::::::::::::::::
::https://stackoverflow.com/questions/4339649/how-to-have-multiple-colors-in-a-windows-batch-file
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
:color
for /F "tokens=1,2 delims=#" %%a in ('"prompt #$H#$E# & echo on & for %%b in (1) do rem"') do (
  set "DEL=%%a"
)
rem Prepare a file "X" with only one dot
<nul > X set /p ".=."
:: %1 颜色,%2~5输出内容
call :colorset %1 %2 %3 %4 %5
exit /b

:colorset
set "param=^%~2 %~3 %~4 %~5" !
set "param=!param:"=\"!"
findstr /p /A:%1 "." "!param!\..\X" nul
<nul set /p ".=%DEL%%DEL%%DEL%%DEL%%DEL%%DEL%%DEL%"
echo.
exit /b
:::::::::::::::::::::::start:::::::::::::::::::::::start:::::::::::::::::::::::
:start
cls
::!!!添加你自己的kms服务地址!!!
::set kmsserver=kms.yourdomain.com
set kmsserver=kms.yourdomain.com
if not defined kmsserver goto connectfail
echo 检查能否连接到公司KMS服务器……
::万能的ping >. <
ping -n 3 %kmsserver% > nul 2>&1
if %errorlevel% neq 0 (
    echo 公司KMS服务器连接失败,检查外部KMS服务器
    set kmsserver=kms.ghpym.com
    echo 检查能否连接到外部KMS服务器……
    ::万能的ping >. <
    ping -n 3 %kmsserver% > nul 2>&1 goto connectfail
)
echo.
call :color 0a 连接到KMS服务器成功
echo.
goto office

:connectfail
cls
echo.
echo =====================================================
call :color 04 无法连接到服务器……
call :color 04 此脚本需要结合kms服务,请勿单独使用!!!
call :color 04 请确保已经正确配置kms服务,并设置变量 kmsserver !!!
echo =====================================================
echo.
pause
goto :eof

:office
echo 开始激活office
echo 注意:只能激活默认安装路径(C:\Program Files)的office
if exist "%ProgramFiles%\Microsoft Office\Office16\ospp.vbs" set officepath=%ProgramFiles%\Microsoft Office\Office16 & set officever=office2016 x64
if exist "%ProgramFiles(x86)%\Microsoft Office\Office16\ospp.vbs" set officepath=%ProgramFiles(x86)%\Microsoft Office\Office16 & set officever=office2016 x32
if exist "%ProgramFiles%\Microsoft Office\Office19\ospp.vbs" set officepath=%ProgramFiles%\Microsoft Office\Office19 & set officever=office2019 x64
if exist "%ProgramFiles(x86)%\Microsoft Office\Office19\ospp.vbs" set officepath=%ProgramFiles(x86)%\Microsoft Office\Office19 & set officever=office2019 x32
cd /d %officepath%
cscript //Nologo ospp.vbs /act | find /i "ERR" > nul && goto activeoffice
echo.
call :color 0a %officever%已经激活,无须再激活
echo.
cd /d "%~dp0"
pause
goto :eof

:activeoffice
echo %officever% | find /I "office2016" && goto licens16
echo %officever% | find /I "office2019" && goto licens19

:licens16
if exist "..\root\" (
  echo 转换office为 vol 版本...
  for /f %%x in ('dir /b ..\root\Licenses16\project???vl_kms*.xrm-ms') do cscript //Nologo ospp.vbs /inslic:"..\root\Licenses16\%%x" >nul
  for /f %%x in ('dir /b ..\root\Licenses16\proplusvl_kms*.xrm-ms') do cscript //Nologo ospp.vbs /inslic:"..\root\Licenses16\%%x" >nul
  for /f %%x in ('dir /b ..\root\Licenses16\standardvl_kms*.xrm-ms') do cscript //Nologo ospp.vbs /inslic:"..\root\Licenses16\%%x" >nul
  for /f %%x in ('dir /b ..\root\Licenses16\visio???vl_kms*.xrm-ms') do cscript //Nologo ospp.vbs /inslic:"..\root\Licenses16\%%x" >nul
  for /f %%x in ('dir /b ..\root\Licenses16\project???vl_mak*.xrm-ms') do cscript //Nologo ospp.vbs /inslic:"..\root\Licenses16\%%x" >nul
  for /f %%x in ('dir /b ..\root\Licenses16\proplusvl_mak*.xrm-ms') do cscript //Nologo ospp.vbs /inslic:"..\root\Licenses16\%%x" >nul
  for /f %%x in ('dir /b ..\root\Licenses16\standardvl_mak*.xrm-ms') do cscript //Nologo ospp.vbs /inslic:"..\root\Licenses16\%%x" >nul
  for /f %%x in ('dir /b ..\root\Licenses16\visio???vl_mak*.xrm-ms') do cscript //Nologo ospp.vbs /inslic:"..\root\Licenses16\%%x" >nul
)
::Visio Professional 2016
cscript //Nologo ospp.vbs /inpkey:PD3PC-RHNGV-FXJ29-8JK7D-RJRJK >nul
::office Professional 2016
cscript //Nologo ospp.vbs /inpkey:QCKNG-29MKJ-74G4B-X7DT8-JFHBB >nul
cscript //Nologo ospp.vbs /inpkey:2xd8d-6VnBw-G9CwQ-K3RT4-w8GdY >nul
cscript //Nologo ospp.vbs /inpkey:XQNVK-8JYDB-WJ9W3-YJ8YR-WFG99 >nul


:licens19
if exist "..\root\" (
  echo 转换office为 vol 版本...
  for /f %%x in ('dir /b ..\root\Licenses16\ProPlus2019VL*.xrm-ms') do cscript //Nologo ospp.vbs /inslic:"..\root\Licenses16\%%x" >nul
  for /f %%x in ('dir /b ..\root\Licenses16\ProPlus2019VL*.xrm-ms') do cscript //Nologo ospp.vbs /inslic:"..\root\Licenses16\%%x" >nul
)
cscript //Nologo ospp.vbs /inpkey:NMMKJ-6RK4F-KMJVX-8D9MJ-6MWKP >nul
cscript //Nologo ospp.vbs /inpkey:6NWWJ-YQWMR-QKGCB-6TMB3-9D9HK >nul
cscript //Nologo ospp.vbs /inpkey:9BGNQ-K37YR-RQHF2-38RQ3-7VCBB >nul

echo 激活中...
cscript //Nologo ospp.vbs /sethst:%kmsserver% > nul
cscript //Nologo ospp.vbs /act | find /i "successful" > nul || goto activeofficefail
echo.
call :color 0a %officever%激活成功
echo.
cd /d "%~dp0"
pause
goto :eof

:activeofficefail
cls
echo.
call :color 04 %officever%激活失败
echo.
cd /d "%~dp0"
pause
goto :eof

三、使用winform写exe工具激活

using Microsoft.Win32;
using System;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.IO;
using System.Linq;
using System.Net.NetworkInformation;
using System.Runtime.InteropServices;
using System.Threading;
using System.Windows.Forms;
using Timer = System.Windows.Forms.Timer;

namespace template
{
    public partial class ActiveTool : Form
    {
        //文字闪烁
        private Timer timer;
        private bool isLabelVisible;
        //文字闪烁

        //窗体移动
        private bool isDragging = false;
        private Point lastCursorPos;
        private Point lastFormPos;
        //窗体移动

        //窗体美化
        private const int CS_DropSHADOW = 0x20000;
        private const int GCL_STYLE = (-26);
        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        public static extern int SetClassLong(IntPtr hwnd, int nIndex, int dwNewLong);
        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        public static extern int GetClassLong(IntPtr hwnd, int nIndex);
        //窗体美化

        private static readonly string[] LicensePatterns =
        {
            "proplusvl_kms*.xrm-ms",
            "proplusvl_mak*.xrm-ms",
            "ProPlus2019VL_KMS*.xrm-ms",
            "ProPlus2019VL_MAK*.xrm-ms"
        };

        private static readonly string[] ProductKeys =
        {
            "NMMKJ-6RK4F-KMJVX-8D9MJ-6MWKP",
            "6NWWJ-YQWMR-QKGCB-6TMB3-9D9HK",
            "9BGNQ-K37YR-RQHF2-38RQ3-7VCBB"
        };

        private const string KmsServerAddress = "kms.yourdomain.com";
        private const int KmsServerPort = 1688;


        public ActiveTool()
        {
            InitializeComponent();

            //文字闪烁
            InitializeTimer();
            //文字闪烁

            MouseDown += Form1_MouseDown;

            GraphicsPath path = new GraphicsPath();
            path.AddArc(0, 0, 40, 40, 180, 90);
            path.AddArc(this.Width - 40, 0, 40, 40, 270, 90);
            path.AddArc(this.Width - 40, this.Height - 40, 40, 40, 0, 90);
            path.AddArc(0, this.Height - 40, 40, 40, 90, 90);
            path.CloseFigure();
            this.Region = new Region(path);

            SetClassLong(this.Handle, GCL_STYLE, GetClassLong(this.Handle, GCL_STYLE) | CS_DropSHADOW);
        }
        //文字闪烁
        private void InitializeTimer()
        {
            timer = new Timer();
            timer.Interval = 500; // 闪烁间隔,单位为毫秒
            timer.Tick += Timer_Tick;
        }
        private void Timer_Tick(object sender, EventArgs e)
        {
            isLabelVisible = !isLabelVisible;
            uiLabel1.Visible = isLabelVisible;
        }
        //文字闪烁

        private void Form1_MouseDown(object sender, MouseEventArgs e)
        {
            //mouseOffset = new Point(-e.X, -e.Y);
            if (e.Button == MouseButtons.Left)
            {
                isDragging = true;
                lastCursorPos = Cursor.Position;
                lastFormPos = Location;
            }
        }

        private void Form1_MouseMove(object sender, MouseEventArgs e)
        {
            if (isDragging)
            {
                int deltaX = Cursor.Position.X - lastCursorPos.X;
                int deltaY = Cursor.Position.Y - lastCursorPos.Y;
                Location = new Point(lastFormPos.X + deltaX, lastFormPos.Y + deltaY);
            }
        }
        private void Form1_MouseUp(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                isDragging = false;
            }
        }
        private void button1_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

            // 隐藏等待效果
            pictureBox2.Invoke(new Action(() =>
            {
                pictureBox2.Visible = false;               
            }));
        }


        private void uiButton5_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }


        private void uiButton2_Click(object sender, EventArgs e)
        {
            // 创建一个新的线程
            Thread thread = new Thread(new ThreadStart(OfficeActivation));
            // 设置为后台线程,主线程结束后自动退出
            thread.IsBackground = true;
            // 启动线程
            thread.Start();

            timer.Start();
            // 显示等待效果
            pictureBox2.Visible = true;
        }


        //获取office32位或者64位的安装路径
        public static string GetOfficeInstallationPath()
        {
            string officePath = null;

            // 64位 Office 安装路径
            officePath = GetOfficeInstallationPathFromRegistry(RegistryView.Registry64);

            // 如果未找到 64位 Office 安装路径,则尝试找到 32位 Office 安装路径
            if (string.IsNullOrEmpty(officePath))
            {
                officePath = GetOfficeInstallationPathFromRegistry(RegistryView.Registry32);
            }
            return officePath;
        }

        //通过注册表获取office的安装路径
        private static string GetOfficeInstallationPathFromRegistry(RegistryView registryView)
        {
            string officePath = null;

            // 根据 Office 版本进行相应的更改
            string officeKey = @"SOFTWARE\Microsoft\Office\ClickToRun\Configuration";

            using (RegistryKey registryKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, registryView))
            {
                using (RegistryKey officeRegistryKey = registryKey.OpenSubKey(officeKey))
                {
                    if (officeRegistryKey != null)
                    {
                        officePath = officeRegistryKey.GetValue("InstallationPath") as string;
                    }
                }
            }

            return officePath;
        }

        //主要激活程序
        private void OfficeActivation()
        {
            //程序执行过程的效果
            Invoke(new Action(() =>
            {
                uiLabel1.Text = "激活中,请稍等";
                uiLabel1.Font = new Font("幼圆", 14, FontStyle.Bold);
                uiButton2.Text = "正在激活...";
                uiButton2.Enabled = false;
            }));

            //检查kms连接状态

            CheckDomainConnection(KmsServerAddress);

            //获取ospp.vbs的路径
            string osppVbsPath = Path.Combine(GetOfficeInstallationPath(),"Office16","ospp.vbs");
            //如果存在ospp.vbs路径
            if (File.Exists(osppVbsPath))
            {
                //安装证书
                InstallLicenses(osppVbsPath);
                InstallProductKeys(osppVbsPath);
                SetKmsServer(osppVbsPath);
                //激活
                ActivateOffice(osppVbsPath);

            }
            else
            {
                MessageBox.Show("未找到office的安装路径", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void FinishProcess()
        {
            // 操作完成后的效果
            pictureBox2.Invoke(new Action(() =>
            {
                pictureBox2.Visible = false;
                uiLabel1.Text = "激活工具";
                uiLabel1.Font = new Font("幼圆", 18, FontStyle.Bold);
                uiButton2.Text = "office激活";
                uiButton2.Enabled = true;
                //文字闪烁
                timer.Stop();
                uiLabel1.Visible = true;
                //文字闪烁
            }));
            // 操作完成后的效果
        }

        //判断kms是否能连接
        private void CheckDomainConnection(string domain)
        {
            try
            {
                using (Ping ping = new Ping())
                {
                    PingReply reply = ping.Send(domain);
                    bool isConnected = (reply.Status == IPStatus.Success);
                    if (!isConnected)
                    {
                        MessageBox.Show("公司的kms服务器无法连接");
                        Application.Exit();
                    }

                }
            }
            catch (Exception)
            {
                MessageBox.Show("连接公司kms服务出错");
            }
        }

        private void InstallLicenses(string officePath)
        {
            //证书路径C:\Program Files\Microsoft Office\root\Licenses16
            string licensesPath = Path.Combine(GetOfficeInstallationPath(), "root", "Licenses16");

            foreach (string pattern in LicensePatterns)
            {
                string[] licenses = Directory.GetFiles(licensesPath, pattern);
                InstallLicenses(licenses);
            }
        }

        private void InstallLicenses(string[] licenses)
        {
            foreach (string license in licenses)
            {
                RunOsppCommand($"/inslic:\"{license}\"");
            }
        }

        private void InstallProductKeys(string officePath)
        {
            foreach (string productKey in ProductKeys)
            {
                RunOsppCommand($"/inpkey:{productKey}");
            }
        }

        private void SetKmsServer(string officePath)
        {
            RunOsppCommand($"/sethst:{KmsServerAddress}");
            RunOsppCommand($"/setprt:{KmsServerPort}");
        }

        private void ActivateOffice(string officePath)
        {
            string result;
            do
            {
                result = RunOsppCommand("/act");
                if (result.Contains("ERR"))
                {
                    string ErrKey = GetErrorKey(result);
                    RunOsppCommand($"/unpkey:{ErrKey}");
                }
            } while (result.Contains("ERR"));

            if (!string.IsNullOrEmpty(result) && result.Contains("successful"))
            {
                FinishProcess();
                MessageBox.Show("office激活成功", "success", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else
            {
                FinishProcess();
                MessageBox.Show("激活时发生未知错误", "未知错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                Application.Exit();  // 退出程序
            }
        }

        private string GetErrorKey(string result)
        {
            string[] lines = result.Split('\n');
            string errKey = "";

            for (int i = 1; i < lines.Length; i++) // 从索引1开始,无需检查第一行
            {
                if (lines[i].Contains("ERROR CODE: 0xC004F017"))
                {
                    string previousLine = lines[i - 1];
                    int startIndex = Math.Max(previousLine.Length - 5, 0); // 使用Math.Max确保startIndex不小于0
                    errKey = previousLine.Substring(startIndex);
                    break;
                }
            }

            return errKey;
        }

        private string RunOsppCommand(string arguments)
        {
            try
            {
                ProcessStartInfo startInfo = new ProcessStartInfo
                {
                    FileName = "cscript.exe",
                    Arguments = $"/nologo \"{Path.Combine(GetOfficeInstallationPath(), "Office16", "ospp.vbs")}\" {arguments}",
                    CreateNoWindow = true,
                    UseShellExecute = false,
                    RedirectStandardOutput = true
                };

                using (Process process = Process.Start(startInfo))
                {
                    process.WaitForExit();
                    if (process.ExitCode != 0)
                    {
                        throw new Exception("ospp.vbs命令执行失败");
                    }

                    string output = process.StandardOutput.ReadToEnd();
                    return output.Trim();
                }
            }
            catch (Exception ex)
            {
                FinishProcess();
                MessageBox.Show($"Error: {ex.Message}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return string.Empty;
            }
        }

        private void uiButton1_Click(object sender, EventArgs e)
        {
            // 创建一个新的线程
            Thread thread = new Thread(new ThreadStart(MainActiveWin));
            // 设置为后台线程,主线程结束后自动退出
            thread.IsBackground = true;
            // 启动线程
            thread.Start();

            timer.Start();
            // 显示等待效果
            pictureBox2.Visible = true;
        }

        private void MainActiveWin()
        {
            //程序执行过程的效果
            Invoke(new Action(() =>
            {
                uiLabel1.Text = "激活中,请稍等";
                uiLabel1.Font = new Font("幼圆", 14, FontStyle.Bold);
                uiButton1.Text = "正在激活...";
                uiButton1.Enabled = false;
            }));

            //检查kms连接状态

            CheckDomainConnection(KmsServerAddress);

            //开始激活
            MainActivate();

            // 操作完成后的效果
            pictureBox2.Invoke(new Action(() =>
            {
                uiButton1.Enabled = true;
                pictureBox2.Visible = false;
                uiLabel1.Text = "激活工具";
                uiLabel1.Font = new Font("幼圆", 18, FontStyle.Bold);
                uiButton1.Text = "Windows激活";
                //文字闪烁
                timer.Stop();
                uiLabel1.Visible = true;
                //文字闪烁
            }));
        }

        private void MainActivate()
        {
            string result = RunCommand("cscript", $"//Nologo {Environment.SystemDirectory}\\slmgr.vbs /xpr");
            if (result.Contains("永久激活") || result.Contains("批量激活"))
            {
                FinishProcess();
                MessageBox.Show("系统已经激活,无需重新激活", "激活成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else
            {
                ActivateWindows();
            }

        }

        private void ActivateWindows()
        {
            string output = RunCommand("reg", "query \"HKLM\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\" /v ProductName");
            string[] lines = output.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
            string productName = lines.FirstOrDefault(line => line.Contains("ProductName"));
            if (productName != null)
            {
                string winversion = productName.Split(new[] { "ProductName" }, StringSplitOptions.RemoveEmptyEntries)[1].Trim();

                if (winversion.Contains("Windows Server 2016 Datacenter"))
                {
                    string pkey = "CB7KF-BWN84-R7R2Y-793K2-8XDDG";
                    string winVersion = "Windows Server 2016 Datacenter";
                    ToActivateWindows(winVersion, pkey);

                }
                else if (winversion.Contains("Windows Server 2016 Standard"))
                {
                    string pkey = "WC2BQ-8NRM3-FDDYY-2BFGV-KHKQY";
                    string winVersion = "Windows Server 2016 Standard";
                    ToActivateWindows(winVersion, pkey);
                }
                else if (winversion.Contains("Windows Server 2016 Essentials"))
                {
                    string pkey = "JCKRF-N37P4-C2D82-9YXRT-4M63B";
                    string winVersion = "Windows Server 2016 Essentials";
                    ToActivateWindows(winVersion, pkey);
                }
                else if (winversion.Contains("Windows Server 2019 Datacenter"))
                {
                    string pkey = "WMDGN-G9PQG-XVVXX-R3X43-63DFG";
                    string winVersion = "Windows Server 2019 Datacenter";
                    ToActivateWindows(winVersion, pkey);
                }
                else if (winversion.Contains("Windows Server 2019 Standard"))
                {
                    string pkey = "N69G4-B89J2-4G8F4-WWYCC-J464C";
                    string winVersion = "Windows Server 2019 Standard";
                    ToActivateWindows(winVersion, pkey);
                }
                else if (winversion.Contains("Windows Server 2019 Essentials"))
                {
                    string pkey = "WVDHN-86M7X-466P6-VHXV7-YY726";
                    string winVersion = "Windows Server 2019 Essentials";
                    ToActivateWindows(winVersion, pkey);
                }
                else if (winversion.Contains("Windows 10 Pro"))
                {
                    string pkey = "W269N-WFGWX-YVC9B-4J6C9-T83GX";
                    string winVersion = "Windows 10 Pro";
                    ToActivateWindows(winVersion, pkey);
                }
                else if (winversion.Contains("Windows 10 Pro N"))
                {
                    string pkey = "MH37W-N47XK-V7XM9-C7227-GCQG9";
                    string winVersion = "Windows 10 Pro N";
                    ToActivateWindows(winVersion, pkey);
                }
                else if (winversion.Contains("Windows 10 Pro Workstations"))
                {
                    string pkey = "NRG8B-VKK3Q-CXVCJ-9G2XF-6Q84J";
                    string winVersion = "Windows 10 Pro Workstations";
                    ToActivateWindows(winVersion, pkey);
                }
                else if (winversion.Contains("Windows 10 Pro Workstations N"))
                {
                    string pkey = "9FNHH-K3HBT-3W4TD-6383H-6XYWF";
                    string winVersion = "Windows 10 Pro Workstations N";
                    ToActivateWindows(winVersion, pkey);
                }
                else if (winversion.Contains("Windows 10 Pro Education"))
                {
                    string pkey = "6TP4R-GNPTD-KYYHQ-7B7DP-J447Y";
                    string winVersion = "Windows 10 Pro Education";
                    ToActivateWindows(winVersion, pkey);
                }
                else if (winversion.Contains("Windows 10 Pro Education N"))
                {
                    string pkey = "YVWGF-BXNMC-HTQYQ-CPQ99-66QFC";
                    string winVersion = "Windows 10 Pro Education N";
                    ToActivateWindows(winVersion, pkey);
                }
                else if (winversion.Contains("Windows 10 Education"))
                {
                    string pkey = "NW6C2-QMPVW-D7KKK-3GKT6-VCFB2";
                    string winVersion = "Windows 10 Education";
                    ToActivateWindows(winVersion, pkey);
                }
                else if (winversion.Contains("Windows 10 Education N"))
                {
                    string pkey = "2WH4N-8QGBV-H22JP-CT43Q-MDWWJ";
                    string winVersion = "Windows 10 Education N";
                    ToActivateWindows(winVersion, pkey);
                }
                else if (winversion.Contains("Windows 10 Enterprise"))
                {
                    string pkey = "NPPR9-FWDCX-D2C8J-H872K-2YT43";
                    string winVersion = "Windows 10 Enterprise";
                    ToActivateWindows(winVersion, pkey);
                }
                else if (winversion.Contains("Windows 10 Enterprise N"))
                {
                    string pkey = "DPH2V-TTNVB-4X9Q3-TJR4H-KHJW4";
                    string winVersion = "Windows 10 Enterprise N";
                    ToActivateWindows(winVersion, pkey);
                }
                else if (winversion.Contains("Windows 10 Enterprise G"))
                {
                    string pkey = "YYVX9-NTFWV-6MDM3-9PT4T-4M68B";
                    string winVersion = "Windows 10 Enterprise G";
                    ToActivateWindows(winVersion, pkey);
                }
                else if (winversion.Contains("Windows 10 Enterprise G N"))
                {
                    string pkey = "44RPN-FTY23-9VTTB-MP9BX-T84FV";
                    string winVersion = "Windows 10 Enterprise G N";
                    ToActivateWindows(winVersion, pkey);
                }
                else
                {
                    FinishProcess();
                    MessageBox.Show("QAQ不支持的系统版本……", "不支持的系统版本", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            else
            {
                FinishProcess();
                MessageBox.Show("QAQ不支持的系统版本……", "不支持的系统版本", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private string RunCommand(string command, string arguments)
        {
            ProcessStartInfo startInfo = new ProcessStartInfo
            {
                FileName = command,
                Arguments = arguments,
                RedirectStandardOutput = true,
                UseShellExecute = false,
                CreateNoWindow = true
            };

            using (Process process = new Process())
            {
                process.StartInfo = startInfo;
                process.Start();
                string output = process.StandardOutput.ReadToEnd();
                process.WaitForExit();
                return output;
            }
        }
        private void ToActivateWindows(string winVersion, string productKey)
        {
            RunCommand("cscript", $"//Nologo {Environment.SystemDirectory}\\slmgr.vbs -ipk {productKey}");
            RunCommand("cscript", $"//Nologo {Environment.SystemDirectory}\\slmgr.vbs /skms {KmsServerAddress}");
            RunCommand("cscript", $"//Nologo {Environment.SystemDirectory}\\slmgr.vbs /ato");

            string result = RunCommand("cscript", $"//Nologo {Environment.SystemDirectory}\\slmgr.vbs /xpr");
            if (result.Contains("未激活") || result.Contains("处于通知模式"))
            {
                FinishProcess();
                MessageBox.Show("系统激活失败", "系统激活失败", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else
            {
                FinishProcess();
                MessageBox.Show($"系统版本为:{winVersion}\n{productKey}\n系统已激活成功", "系统激活成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        private void pictureBox2_Click(object sender, EventArgs e)
        {
            MessageBox.Show("本激活工具只合适公司内使用:\nWindows支持激活的版本有\nServer 2016\nServer 2019\nWindows 10(部分版本)\noffice支持激活的版本有:\noffice2016\noffice2019", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        private void pictureBox1_Click_1(object sender, EventArgs e)
        {
            MessageBox.Show("本激活工具只合适公司内使用:\nWindows支持激活的版本有\nServer 2016\nServer 2019\nWindows 10(部分版本)\noffice支持激活的版本有:\noffice2016\noffice2019", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
    }
}

 

标签:pkey,set,string,Windows,echo,自行,kms,winversion%,搭建
From: https://www.cnblogs.com/yujiastudio/p/17680295.html

相关文章

  • 前端项目环境搭建笔记
    @目录简介一、vue3组件通信方式1.1props1.2自定义事件1.2.1原生DOM事件1.2.2自定义事件1.3全局事件总线1.4v-model1.5useAttrs1.6ref与$parent1.7provide与inject1.8pinia1.9slot二、搭建后台管理系统模板2.1项目初始化2.1.1环境准备2.1.2初始化项目2.2项目配置一、eslint......
  • 搭建Ubuntu 22.04可视化界面
    执行以下命令,清空缓存,更新您的软件包列表。sudoaptcleanall&&sudoaptupdate执行以下命令,安装桌面环境所需软件包。包括系统面板、窗口管理器、文件浏览器、终端等桌面应用程序。sudoaptinstallgnome-panelgnome-settings-daemonmetacitynautilusgnome-terminal......
  • Linux搭建GitLab私有仓库
    前言GitLab是一个用于仓库管理系统的开源项目,使用Git作为代码管理工具,并在此基础上搭建起来的Web服务。Gitlab是被广泛使用的基于git的开源代码管理平台,基于RubyonRails构建,主要针对软件开发过程中产生的代码和文档进行管理,Gitlab主要针对group和project两个维度进行代......
  • rocetmq搭建控制台
    1.概述使用单机版进行搭建社区提供了控制台:https://github.com/apache/rocketmq-dashboardmvncleanpackage-Dmaven.test.skip=true 2.环境变量但是这个时候要注意,在这个项目的application.yml中需要指定nameserver的地址。默认这个属性是指向本地。如果......
  • ELK-windows搭建笔记
    一、        介绍Elasticsearch:开源分布式搜索引擎,它的特点有:分布式,零配置,自动发现,索引自动分片,索引副本机制,restful风格接口,多数据源,自动搜索负载等。Logstash:对你的日志进行收集、过滤,并将其存储供以后使用(如,搜索)。Kibana:以为Logstash和ElasticSearch提供......
  • Hadoop大数据平台搭建
    Hadoop平台搭建了解Hadoop一、Hadoop是什么?Hadoop是一个由Apache基金会所开发的分布式系统基础架构,是一个存储系统+计算框架的软件框架。主要解决海量数据存储与计算的问题,是大数据技术中的基石。Hadoop以一种可靠、高效、可伸缩的方式进行数据处理,用户可以在不了解分布式底......
  • 项目开发环境搭建手记(2.Jdk安装——替代原有的OpenJDK)
    作者:fbysss前言:Centos下,Java已经安装好了,1.7版本的,但是并没有JAVA_HOME等环境变量。于是:exportJAVA_HOME=/usr/lib/jvm/java-1.7.0-openjdk-1.7.0.9exportCLASSPATH=.:$JAVA_HOME/jre/lib/rt.jar:$JAVA_HOME/lib/dt.jar:$JAVA_HOME/lib/tools.jarexportPATH=$PATH:$JAVA_HOME......
  • 云原生环境搭建第三篇:Ceph存储
    云原生环境搭建第三篇:Ceph存储原创 杨同港 者行花 2023-07-1811:43 发表于山东收录于合集#云原生5个GlusterFS在k8s1.25中被移除,所以开源的,社区活跃度高的分布式存储最优选就是ceph,本文使用rook-ceph部署ceph集群。ceph是一个开源的存储平台。它的架构如下:Ceph存......
  • 自建KMS服务器
    转载自好友随遇而安的博文。KMS简介KMS是一种专为中型和大型企业设计的Microsoft产品的激活方法。在标准SOHO环境中,您在安装期间输入产品密钥,然后通过Internet激活产品。这是通过向microsoft.com上的服务器发送请求来完成的,然后该服务器授予或拒绝激活。通过输入......
  • 全开源风车im源码(前端uniapp可发布H5及app/后端java含视频搭建教程)
    互联网彻底改变了我们的沟通方式,电子邮件是迄今为止采用最快的通信形式。不到二十年前,还没有多少人听说过它。现在,我们中的许多人都用电子邮件而不是写信,甚至打电话给别人,世界各地的人们每天发送数十亿封电子邮件。源码:ms.jstxym.top但有时甚至电子邮件也不够快。您可能不知道您......