shell

package
v0.7.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 16, 2026 License: Apache-2.0 Imports: 11 Imported by: 0

Documentation

Overview

Package shell 提供安全的 Shell 脚本执行功能 基于 mvdan/sh interp 实现,替代 os/exec

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func IsShellScript

func IsShellScript(ctx context.Context, script string) (bool, error)

IsShellScript 判断给定的脚本是否是有效的Shell脚本

该函数使用mvdan.cc/sh/v3/syntax包来解析脚本,如果能够成功解析为有效的Shell语法, 则返回true。这比简单的shebang检测更准确,因为: 1. 不依赖shebang(shebang可能缺失或错误) 2. 能够检测语法错误 3. 能够处理复杂的Shell脚本结构

参数:

ctx: 上下文,目前未使用,为未来扩展保留
script: 要检查的脚本内容

返回值:

bool: 如果是有效的Shell脚本返回true,否则返回false
error: 解析过程中的错误信息(如果脚本不是有效的Shell脚本,会返回具体的语法错误)

func SafeExecute

func SafeExecute(ctx context.Context, script string) (string, error)

SafeExecute 安全执行 Shell 脚本(启用沙箱模式)

func SimpleExecute

func SimpleExecute(ctx context.Context, script string) (string, error)

SimpleExecute 简单执行 Shell 脚本(使用默认配置)

Types

type Config

type Config struct {
	// 工作目录
	WorkingDir string

	// 环境变量(如果为空则使用系统环境变量)
	EnvVars []string

	// 默认执行超时
	Timeout time.Duration

	// 最大输出大小(字节)
	MaxOutputSize int

	// 是否启用严格模式(-e -u 参数)
	StrictMode bool

	// 是否启用沙箱模式
	SandboxMode bool

	// 沙箱配置(仅在 SandboxMode=true 时生效)
	SandboxConfig *SandboxConfig
}

Config 执行器配置

func DefaultConfig

func DefaultConfig() *Config

DefaultConfig 返回默认配置

type Executor

type Executor struct {
	// contains filtered or unexported fields
}

Executor Shell 脚本执行器

func NewExecutor

func NewExecutor(config *Config) *Executor

NewExecutor 创建新的执行器

func (*Executor) Execute

func (e *Executor) Execute(ctx context.Context, script string) (*Result, error)

Execute 执行 Shell 脚本

func (*Executor) ExecuteWithTimeout

func (e *Executor) ExecuteWithTimeout(ctx context.Context, script string, timeout time.Duration) (*Result, error)

ExecuteWithTimeout 执行 Shell 脚本(指定超时)

type Result

type Result struct {
	// 标准输出
	Stdout string

	// 标准错误
	Stderr string

	// 退出码
	ExitCode int

	// 执行耗时
	Duration time.Duration

	// 执行错误(如果有)
	Err error

	// 输出是否被截断
	Truncated bool
}

Result 执行结果

type SandboxConfig

type SandboxConfig struct {
	// 允许的命令列表(如果为空则允许所有命令)
	AllowedCommands []string

	// 允许访问的路径列表(如果为空则允许所有路径)
	AllowedPaths []string

	// 允许的环境变量列表(如果为空则允许所有环境变量)
	AllowedEnvVars []string

	// 是否允许网络访问
	AllowNetwork bool

	// 是否允许执行外部程序
	AllowExternalExec bool
}

SandboxConfig 沙箱配置

func DefaultSandboxConfig

func DefaultSandboxConfig() *SandboxConfig

DefaultSandboxConfig 返回默认沙箱配置

Source Files

  • executor.go
  • validator.go

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL