在 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