跳到正文
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