跳到正文
LICENTIVO / INTEGRATION

為無人值守工作的 Go 命令列工具加入授權

在命令列匯出前檢查授權。透過排程工作執行程式,核對結束代碼與實際產生的檔案。

Windows x64 · Go 1.26 · PowerShell更新日期

準備命令列專案

在新資料夾中將範例存成 main.go,填入產品 ID 與受信任公鑰。簽發兩組測試授權碼,僅讓第一組具有 export 權限。

Go · main.go
package main

import (
	"context"
	"fmt"
	"os"

	licentivo "github.com/spf86/licentivo-sdk"
)

const productID = "YOUR_PRODUCT_ID"
const usage = "Usage: report-job export <output.csv>"

var trustedKeys = map[string]string{"YOUR_KEY_ID": "YOUR_PUBLIC_KEY"}

func run(args []string) int {
	if len(args) == 1 && args[0] == "--help" {
		fmt.Println(usage)
		return 0
	}
	if len(args) != 2 || args[0] != "export" {
		fmt.Fprintln(os.Stderr, usage)
		return 64
	}
	client, err := licentivo.OpenProduct(context.Background(), productID, trustedKeys, os.Getenv("LICENTIVO_LICENSE_KEY"), nil)
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		return 2
	}
	defer client.Close()
	err = client.RunFeature("export", func() error {
		return os.WriteFile(args[1], []byte("item,total\nreports,1\n"), 0600)
	})
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		return 2
	}
	fmt.Println(args[1])
	return 0
}

func main() {
	os.Exit(run(os.Args[1:]))
}

建置 Go 執行檔

在專案資料夾執行以下命令。啟用前就能查看說明,確認排程器要傳入的引數。

PowerShell
go mod init example.com/report-job
go get github.com/spf86/licentivo-sdk@v0.11.8
go build -o report-job.exe .
.\report-job.exe --help

讓工作無須互動即可啟用

透過工作執行器的機密儲存區,將第一組授權碼注入 LICENTIVO_LICENSE_KEY。以排程工作的執行帳號完成首次匯出。程式不會等待標準輸入。

PowerShell
.\report-job.exe export first.csv
$LASTEXITCODE
Test-Path -LiteralPath .\first.csv

透過排程工作執行

將指令碼放在執行檔旁,確保工作帳號能寫入該資料夾。之後以同一帳號執行並清除授權碼環境變數。時間戳記會為每份報表產生新檔名。指令碼將程式的結束代碼傳回排程器。

PowerShell · run-report.ps1
$outputFile = Join-Path $PSScriptRoot ("report-{0:yyyyMMdd-HHmmssfff}.csv" -f (Get-Date))
& (Join-Path $PSScriptRoot 'report-job.exe') export $outputFile
exit $LASTEXITCODE

判讀工作失敗的結果

結束代碼 0 表示成功,2 表示授權或匯出失敗,64 表示引數有誤。診斷資訊寫入標準錯誤輸出。切換到新的使用者設定檔,用第二組授權碼和新的輸出路徑執行,預期傳回 2 且沒有報表。

本機以非互動 PowerShell 執行此指令碼。有權限時傳回 0 並產生一份報表,沒有權限時傳回 2 且沒有新檔案。無效的命令引數會讓程式傳回 64。

PowerShell
.\report-job.exe export denied.csv
$LASTEXITCODE
Test-Path -LiteralPath .\denied.csv