跳到正文
LICENTIVO / INTEGRATION

给 PyInstaller 打包的 Python 桌面软件加授权

将报表程序打包成 Windows 可执行文件,在导出前验证授权码。用打包后的程序检查首次激活、重启恢复和无权限时的结果。

Windows x64 · Python 3.12 · PyInstaller 6.22.3更新日期

在 Python 中保护导出操作

将示例保存为 report.py,填入控制台的产品 ID 和受信公钥。为同一产品准备两个测试授权码,只给第一个授权码开通 export 功能。

Python · report.py
import os
import sys
from pathlib import Path

from licentivo import Client


PRODUCT_ID = "YOUR_PRODUCT_ID"
TRUSTED_KEYS = {"YOUR_KEY_ID": "YOUR_PUBLIC_KEY"}


def main(args):
    if len(args) != 1:
        print("Usage: LicenseReport <output.csv>", file=sys.stderr)
        return 64
    output = Path(args[0])
    try:
        with Client.open_product(
            PRODUCT_ID, TRUSTED_KEYS, os.getenv("LICENTIVO_LICENSE_KEY", "")
        ) as client:
            client.run_feature(
                "export", lambda: output.write_text("item,total\nreports,1\n", encoding="utf-8")
            )
    except Exception as error:
        print(error, file=sys.stderr)
        return 2
    print(output)
    return 0


if __name__ == "__main__":
    sys.exit(main(sys.argv[1:]))

生成 Windows 可执行文件

在安装了 Python 3.12 的 Windows x64 构建机上运行以下 PowerShell 命令。dist 目录中的单个可执行文件就是交给测试者的程序。

PowerShell
py -3.12 -m venv .venv
.\.venv\Scripts\python.exe -m pip install "licentivo-sdk==0.11.8" "PyInstaller==6.22.3"
.\.venv\Scripts\python.exe -m PyInstaller --clean --noconfirm --onefile --name LicenseReport report.py

激活打包后的程序

只把 LicenseReport.exe 复制到一台未安装 Python 的 Windows x64 测试机的空目录。在该目录运行命令,在隐藏输入框中输入第一个测试授权码。成功后会生成 first.csv。

PowerShell
$key = Read-Host 'Test license key' -AsSecureString
try {
    $env:LICENTIVO_LICENSE_KEY = [System.Net.NetworkCredential]::new('', $key).Password
    .\LicenseReport.exe first.csv
    $LASTEXITCODE
} finally {
    Remove-Item Env:LICENTIVO_LICENSE_KEY -ErrorAction SilentlyContinue
    $key.Dispose()
}
Test-Path -LiteralPath .\first.csv

用同一 Windows 账号重新启动

清除授权码环境变量后再次运行程序。若生成了新的报表,说明 SDK 已恢复这个 Windows 账号保存的凭证。

PowerShell
.\LicenseReport.exe restart.csv
$LASTEXITCODE
Get-Content -LiteralPath .\restart.csv

验证没有导出权限的授权码

换用全新的 Windows 用户配置文件,用第二个授权码重复激活步骤,将输出文件名改为 denied.csv。预期退出码为 2,文件不会生成。每次检查都用新的文件名。

Windows x64 本地验证使用 CPython 3.12.10 构建,只把 EXE 复制到空目录。运行时从 EXE 的临时解包目录加载 Python,首次激活和重启都写出了报表。无导出权限时返回 2,未创建文件。

PowerShell
# In the fresh profile, supply the second key.
$key = Read-Host 'Test license key' -AsSecureString
try {
    $env:LICENTIVO_LICENSE_KEY = [System.Net.NetworkCredential]::new('', $key).Password
    .\LicenseReport.exe denied.csv
    $LASTEXITCODE
} finally {
    Remove-Item Env:LICENTIVO_LICENSE_KEY -ErrorAction SilentlyContinue
    $key.Dispose()
}
Test-Path -LiteralPath .\denied.csv