gcs

package module
v1.8.11 Latest Latest
Warning

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

Go to latest
Published: Jan 9, 2026 License: Apache-2.0 Imports: 15 Imported by: 14

README

🚀 GCS - Go Command Shell

Go Version License Version

📋 项目简介

GCS (Go Command Shell) 是一个功能强大的 Go 语言系统命令执行模块,提供了类似 Python 的 os.systemsubprocess.getstatusoutputsubprocess.getoutput 的功能。支持普通命令执行、sudo 权限命令、脚本执行、进程管理等多种场景。

✨ 核心特性
  • 🔧 简单易用: 简洁的 API 设计,快速上手
  • 🔐 权限管理: 支持 sudo 权限执行命令
  • 📊 实时输出: 支持命令执行结果的实时打印
  • 📝 脚本支持: 支持复杂脚本和管道命令执行
  • 🖥️ 跨平台: 支持 Linux、Windows、macOS 等主流操作系统
  • 🎯 进程管理: 提供进程状态检测功能
  • 🔍 结果处理: 支持命令输出结果的灵活处理和分析

🚀 快速开始

安装
# 使用最新版本
go get gitee.com/liumou_site/gcs@latest

# 或者指定版本
go get gitee.com/liumou_site/gcs@v1.8.3
基本使用
package main

import (
    "fmt"
    "strings"
    "sync"
    "gitee.com/liumou_site/gcs"
)

func main() {
    // 创建 shell 实例
    shell := gcs.NewShell()
    
    // 执行简单命令
    shell.RunShell("ls", "-la")
    if shell.Err != nil {
        fmt.Printf("执行失败: %v\n", shell.Err)
    } else {
        fmt.Printf("执行成功:\n%s\n", shell.Strings)
    }
}

📖 详细文档

基础命令执行
// 创建 shell 实例
shell := gcs.NewShell()

// 方法 1: 直接执行命令
shell.RunShell("ls -la /home")

// 方法 2: 分参数执行
shell.RunShell("ls", "-la", "/home")

// 方法 3: 执行脚本(支持管道)
shell.RunScript("ps aux | grep nginx")

// 方法 4: 通过终端执行(支持图形界面)
shell.RunTerminal("htop")
Sudo 权限命令
// 创建 sudo 实例(需要提供密码)
sudo := gcs.NewSudo("your-password")

// 开启实时输出
sudo.Realtime = true

// 执行需要 sudo 权限的命令
sudo.RunSudo("apt update")
sudo.RunSudo("systemctl restart nginx")

// 执行脚本
sudo.RunScriptSudo("docker ps -a | grep nginx")
批量命令执行
shell := gcs.NewShell()

// 批量执行命令,遇到错误立即停止
commands := []string{
    "echo '第一步'",
    "ls -la",
    "pwd",
    "echo '完成'",
}
shell.RunShellList(commands)
命令结果处理
shell := gcs.NewShell()
shell.RunShell("docker ps -a")

// 结果过滤
shell.Grep("nginx")           // 过滤包含 nginx 的行
shell.AwkCol("2")             // 获取第2列
shell.Line(1)                   // 获取第1行
shell.Column(3, " ")          // 获取第3列(按空格分隔)

fmt.Println(shell.Strings)     // 输出处理后的结果
进程管理
shell := gcs.NewShell()

// 检查进程是否在运行
if shell.ProcessIsRunning("nginx") {
    fmt.Println("Nginx 正在运行")
} else {
    fmt.Println("Nginx 未运行")
}

⚙️ 配置参数

Shell 配置
参数 类型 默认值 说明
Realtime bool false 实时打印命令执行输出
Debug bool false 开启调试模式,输出详细日志
PrintErr bool true 打印错误信息
PrintInfo bool false 打印详细信息
BlackHole bool false 忽略错误输出(黑洞模式)
Ignore bool false 忽略标准输出
Sudo 配置
参数 类型 说明
Password string sudo 密码
Realtime bool 实时输出模式
Debug bool 调试模式
日志等级配置

GCS 使用专业的日志库进行日志输出管理,支持灵活的日志等级控制。

日志等级说明
等级 代码 优先级 说明
EMER 0 最高 系统级紧急(磁盘出错,内存异常等)
ALRT 1 系统级警告(数据库异常,配置错误等)
CRIT 2 系统级危险(权限出错,访问异常等)
EROR 3 用户级错误
WARN 4 用户级警告
INFO 5 用户级信息(默认等级
DEBG 6 用户级调试(需要手动开启)
TRAC 7 最低 用户级基本输出
设置日志等级
package main

import "gitee.com/liumou_site/gcs"

func main() {
    // 创建实例时自动设置默认日志等级为 INFO
    shell := gcs.NewShell()
    
    // 动态设置日志等级
    gcs.SetLogLevel("DEBG")  // 开启调试模式,输出所有日志
    gcs.SetLogLevel("WARN")  // 只输出警告和错误
    gcs.SetLogLevel("EROR")  // 只输出错误
    gcs.SetLogLevel("INFO")  // 恢复默认等级
    
    // 生产环境推荐配置
    gcs.SetLogLevel("WARN")  // 只显示重要信息
}
使用场景建议
  • 开发调试: SetLogLevel("DEBG") - 输出所有调试信息
  • 测试环境: SetLogLevel("INFO") - 输出基本信息(默认)
  • 生产环境: SetLogLevel("WARN") - 只输出警告和错误
  • 监控环境: SetLogLevel("EROR") - 只输出严重错误
日志输出示例
// 默认 INFO 等级下
shell := gcs.NewShell()
// DEBUG 信息不会显示
// INFO 信息会显示
// WARN 信息会显示
// ERROR 信息会显示

// 设置为 DEBUG 等级后
gcs.SetLogLevel("DEBG")
// 所有级别的日志都会显示

🔧 高级功能

超时控制
shell := gcs.NewShell()

// 设置命令执行超时时间为 10 秒
shell.RunTimeout(10, "ping baidu.com")

// 检查是否超时
if shell.Err != nil {
    fmt.Printf("命令执行失败: %v\n", shell.Err)
    if strings.Contains(shell.Err.Error(), "timeout") {
        fmt.Println("命令执行超时")
    }
}
并发执行
// 并发执行多个命令
shell1 := gcs.NewShell()
shell2 := gcs.NewShell()
shell3 := gcs.NewShell()

var wg sync.WaitGroup
wg.Add(3)

go func() {
    defer wg.Done()
    shell1.RunShell("ping -c 4 baidu.com")
}()

go func() {
    defer wg.Done()
    shell2.RunShell("ping -c 4 google.com")
}()

go func() {
    defer wg.Done()
    shell3.RunShell("ping -c 4 github.com")
}()

wg.Wait()
错误处理
shell := gcs.NewShell()
shell.RunShell("ls", "/nonexistent")

if shell.Err != nil {
    fmt.Printf("命令执行失败: %v\n", shell.Err)
    fmt.Printf("退出代码: %d\n", shell.ExitCode)
}
结果解析
shell := gcs.NewShell()
shell.RunShell("route")

// 获取默认网关
shell.Grep("default").Column(3, " ")
gateway := shell.Strings

fmt.Printf("默认网关: %s\n", gateway)

📊 实际应用示例

系统监控脚本
func SystemMonitor() {
    shell := gcs.NewShell()
    
    // 检查系统负载
    shell.RunShell("uptime")
    fmt.Printf("系统负载: %s\n", shell.Strings)
    
    // 检查磁盘使用
    shell.RunShell("df -h /")
    shell.Grep("/$")
    fmt.Printf("磁盘使用: %s\n", shell.Strings)
    
    // 检查内存使用
    shell.RunShell("free -m")
    shell.Grep("Mem:")
    fmt.Printf("内存信息: %s\n", shell.Strings)
}
Docker 管理
func DockerManager() {
    sudo := gcs.NewSudo("your-password")
    sudo.Realtime = true
    
    // 查看运行中的容器
    sudo.RunSudo("docker ps")
    
    // 停止所有容器
    sudo.RunScriptSudo("docker ps -q | xargs docker stop")
    
    // 清理无用镜像
    sudo.RunSudo("docker system prune -f")
}
软件安装
Linux/macOS 系统
func InstallSoftware(packageName string) {
    sudo := gcs.NewSudo("your-password")
    
    // 更新软件包列表
    sudo.RunSudo("apt update")
    if sudo.Err != nil {
        fmt.Printf("更新失败: %v\n", sudo.Err)
        return
    }
    
    // 安装软件
    sudo.RunSudo("apt install -y", packageName)
    if sudo.Err != nil {
        fmt.Printf("安装失败: %v\n", sudo.Err)
        return
    }
    
    fmt.Printf("%s 安装成功\n", packageName)
}
Windows 系统
func InstallWindowsSoftware() {
    shell := gcs.NewShell()
    
    // 使用 Chocolatey 安装软件(需要先安装 Chocolatey)
    shell.RunShell("choco", "install", "git", "-y")
    
    // 使用 winget 安装软件(Windows 10/11 内置)
    shell.RunShell("winget", "install", "Git.Git")
    
    if shell.Err != nil {
        fmt.Printf("安装失败: %v\n", shell.Err)
        return
    }
    
    fmt.Println("软件安装成功")
}

🧪 测试

项目包含完整的测试用例,可以通过以下命令运行测试:

# 运行所有测试
go test -v

# 运行特定测试
go test -v -run TestShell

# 运行测试并生成覆盖率报告
go test -v -cover

# Windows 用户
# 在 PowerShell 中运行
go test -v

测试覆盖的功能包括:

  • ✅ 基础命令执行
  • ✅ Sudo 权限命令
  • ✅ 脚本执行
  • ✅ 结果处理
  • ✅ 进程管理
  • ✅ 错误处理
  • ✅ 超时控制
  • ✅ 跨平台兼容性

🤝 贡献

欢迎提交 Issue 和 Pull Request!

开发环境
# 克隆项目
git clone https://gitee.com/liumou_site/gcs.git

# 进入项目目录
cd gcs

# 安装依赖
go mod download

# 运行测试
go test -v

# Windows PowerShell
git clone https://gitee.com/liumou_site/gcs.git
cd gcs
go mod download
go test -v

📄 许可证

本项目基于 Apache License 2.0 许可证开源。

💬 问题反馈


⭐ 如果这个项目对你有帮助,请给个 Star 支持一下!

🛠️ Windows 用户特别说明

系统要求
  • Windows 10/11 专业版或企业版
  • PowerShell 5.0 或更高版本
  • 建议使用 Windows Terminal 获得最佳体验
Windows 特定配置
// Windows 系统下自动使用 cmd.exe
shell := gcs.NewShell()

// 执行 Windows 特定命令
shell.RunShell("dir", "/w")           // 宽格式显示目录
shell.RunShell("tasklist")           // 查看进程列表
shell.RunShell("netstat", "-an")     // 查看网络连接

// Windows 服务管理
shell.RunShell("sc", "query", "w32time")  // 查看时间服务状态
shell.RunShell("net", "start")           // 查看正在运行的服务
注意事项
  1. 路径分隔符: Windows 使用反斜杠 \,建议使用双反斜杠或原始字符串
  2. 管理员权限: 在 Windows 上执行需要管理员权限的命令时,需要以管理员身份运行程序
  3. 编码问题: Windows 默认使用 GBK 编码,可能需要设置控制台编码为 UTF-8
性能优化建议
  • 对于频繁执行的命令,建议复用 ApiShell 实例
  • 大量并发命令执行时,建议使用 goroutine 池
  • 实时输出模式 (Realtime = true) 会略微降低性能,但在需要即时反馈的场景下推荐使用

🔧 常见问题解答 (FAQ)

Q: 在 Windows 上执行命令出现乱码?

A: 这是编码问题,可以在程序开始时设置控制台编码:

import "golang.org/x/text/encoding/simplifiedchinese"
// 设置控制台为 UTF-8 编码
exec.Command("cmd", "/c", "chcp 65001").Run()
Q: 为什么有些命令执行失败?

A: 可能原因:

  1. 命令不在系统 PATH 中
  2. 缺少必要的权限
  3. 命令语法在不同平台上有差异
  4. 防病毒软件阻止了命令执行
Q: 如何调试命令执行问题?

A: 开启调试模式并设置日志等级为 DEBUG:

shell := gcs.NewShell()
shell.Debug = true      // 开启调试输出
shell.PrintErr = true   // 打印错误信息
shell.PrintInfo = true  // 打印详细信息

// 设置日志等级为 DEBUG 以查看详细日志
import "gitee.com/liumou_site/gcs"
gcs.SetLogLevel("DEBG")  // 输出所有调试信息
Q: 如何控制日志输出量?

A: 使用 SetLogLevel 函数动态调整日志等级:

import "gitee.com/liumou_site/gcs"

// 生产环境 - 只显示警告和错误
gcs.SetLogLevel("WARN")

// 开发环境 - 显示所有信息
gcs.SetLogLevel("DEBG")

// 监控环境 - 只显示严重错误
gcs.SetLogLevel("EROR")
Q: 默认的日志等级是什么?

A: 默认日志等级为 INFO,只输出 INFO 及以上级别的日志(包括 WARN、ERROR 等)。DEBUG 级别的日志需要手动开启。

Q: 支持哪些 Go 版本?

A: 最低支持 Go 1.19,推荐使用最新稳定版本以获得最佳性能和安全性。

Q: 是否支持 PowerShell Core?

A: 是的,GCS 完全支持 PowerShell Core (PowerShell 7+),在 Windows 上会自动检测并使用最适合的 shell。

Q: 如何处理中文路径?

A: GCS 支持 Unicode 路径,但在 Windows 上建议使用 UTF-8 编码:

// 设置控制台为 UTF-8
exec.Command("cmd", "/c", "chcp 65001").Run()

// 使用 UTF-8 路径
shell.RunShell("dir", "C:\\用户\\文档")

Documentation

Index

Constants

View Source
const (
	SudoAuthNotChecked   = "未进行验证"   // 初始状态
	SudoAuthSuccess      = "验证成功"    // 验证成功
	SudoAuthWrongPass    = "密码错误"    // 密码错误
	SudoAuthNoPermission = "无sudo权限" // 无sudo权限
)

SudoAuthStatus 定义sudo验证状态常量

Variables

View Source
var Debug bool = false

Debug 全局调试变量,控制是否输出调试信息

Functions

func CheckCmd

func CheckCmd(cmd string) bool

CheckCmd 检查命令是否存在

func GetUserInfo

func GetUserInfo(display bool) (ok bool, username string, userid int, UserHome string)

GetUserInfo 获取用户名,用户uid,用户家目录

@Description:
@param display 是否显示详细信息
@return ok 获取结果
@return username 用户名
@return userid 用户ID
@return UserHome 用户主目录

func SetLogLevel added in v1.8.5

func SetLogLevel(level string)

SetLogLevel 设置日志输出等级

@Description:
@param level 日志等级字符串,支持以下值:
	"EMER" - 系统级紧急(磁盘出错,内存异常等)
	"ALRT" - 系统级警告(数据库异常,配置错误等)
	"CRIT" - 系统级危险(权限出错,访问异常等)
	"EROR" - 用户级错误
	"WARN" - 用户级警告
	"INFO" - 用户级信息(默认)
	"DEBG" - 用户级调试(需要手动开启)
	"TRAC" - 用户级基本输出

func Version

func Version() string

Version

@Description: 记录模块版本
@return string

Types

type ApiHandle added in v1.5.7

type ApiHandle struct {
	Strings string   // 处理结果
	Err     error    // 错误
	Slice   []string // 切片
}

type ApiShell added in v1.4.7

type ApiShell struct {
	Realtime bool   // 是否开启实时打印信息
	Result   bool   // 是否执行成功
	Text     string // 需要执行的命令
	OsType   string // 系统类型

	Strings  string // 输出结果
	ExitCode int    // 命令执行退出代码
	Err      error  // 错误

	Slice      []string // 数据切片
	Script     string   // 脚本文件
	ScriptMode bool     // 脚本文件

	Terminal     string // 使用的终端命令
	TerminalArg  string // 使用的终端参数
	TerminalBool bool   // 是否可以使用终端
	BlackHole    bool   // 是否使用黑洞模式(忽略错误信息)
	Ignore       bool   // 是否忽略标准输出
	// contains filtered or unexported fields
}

ApiShell @Description: 定义命令的结构体

func NewShell added in v1.4.6

func NewShell() *ApiShell

NewShell 命令实例构造函数 Realtime 是否开启实时打印数据

@Description:
@return *ApiShell

func (*ApiShell) AwkCol added in v1.7.5

func (api *ApiShell) AwkCol(col string)

AwkCol 提取并打印指定列的数据。 该方法使用 awk 工具从临时文件中提取指定的列,并将结果打印出来。 参数:

col (string): 需要提取的列号,例如 "1" 表示第一列。

func (*ApiShell) Column added in v1.5.5

func (api *ApiShell) Column(col int, sep string) *ApiShell

Column 方法按列解析字符串数据,并使用指定的分隔符。 该方法接收两参数:col(int) 和 sep(string),分别表示列号和分隔符。 它首先将字符串按行分割,然后调用 gfs 的 Column 方法进行列解析, 最后更新 api 的字符串数据和错误信息,并返回 api 实例。

func (*ApiShell) Echo added in v1.5.5

func (api *ApiShell) Echo()

Echo 方法用于打印 ApiShell 实例中的 Strings 属性。 该方法没有输入参数,也不返回任何值。 主要用途是展示或调试 Strings 属性的内容。

func (*ApiShell) Grep added in v1.5.7

func (api *ApiShell) Grep(match string) *ApiShell

Grep 方法用于在 ApiShell 实例的字符串数组中搜索匹配指定文本的行。 它利用 api.gfs 的 Grep 方法进行实际的搜索操作,并更新 ApiShell 实例的状态以反映搜索结果。 参数:

match - 要搜索的字符串。

返回值:

*ApiShell - 返回当前的 ApiShell 实例,用于支持链式调用。

func (*ApiShell) Line added in v1.5.5

func (api *ApiShell) Line(n int) *ApiShell

Line 方法用于处理文本数据,使其以指定的行数显示 参数 n 指定文本应显示的行数 该方法返回 ApiShell 类型的指针,使得方法调用可以链式方式进行

func (*ApiShell) ProcessIsRunning added in v1.8.0

func (api *ApiShell) ProcessIsRunning(command string) bool

ProcessIsRunning 检查指定命令的进程是否正在运行。 参数:

command (string): 需要检测的命令名称。

返回值:

bool: 如果进程正在运行,则返回true;否则返回false。

func (*ApiShell) RunScript added in v1.5.8

func (api *ApiShell) RunScript(command ...string)

RunScript 通过生成脚本的方式执行Shell,支持Shell管道

@Description:
@receiver api
@param command 需要执行的命令,例如 'apt', 'update',命令与选项可以分开传入

func (*ApiShell) RunShell added in v1.4.7

func (api *ApiShell) RunShell(command ...string)

RunShell 执行Shell命令。

该方法接受一个或多个字符串参数作为命令,将其存储在api.args中, 然后调用api.shellSystem()方法来执行命令。 此方法不返回任何值。

func (*ApiShell) RunShellList added in v1.7.7

func (api *ApiShell) RunShellList(cs []string)

RunShellList 批量执行命令

@Description: 通过传入完整的命令切片遍历执行,当遇到执行错误立即返回
@receiver api
@param cs 需要执行的命令切片,每个切片元素必须是完整命令

func (*ApiShell) RunTerminal added in v1.7.8

func (api *ApiShell) RunTerminal(command ...string)

RunTerminal 通过调用图形化终端程序的方式执行Shell命令,使用脚本封装的方式,支持Shell管道

@Description:
@receiver api
@param command 需要执行的命令,例如 'apt', 'update',命令与选项可以分开传入

func (*ApiShell) RunTimeout added in v1.7.4

func (api *ApiShell) RunTimeout(n time.Duration, command ...string) *ApiShell

RunTimeout 执行系统命令并设置超时时间

@Description:
@receiver api
@param n 超时时间(秒)
@param command 需要执行的命令,例如 'apt', 'update',命令与选项可以分开传入
@return *ApiShell

type ApiSudo added in v1.4.7

type ApiSudo struct {
	SudoPath string // sudo命令绝对路径
	Password string // sudo权限使用的密码

	Auth bool // 是否需要认证

	ApiShell // 继承Shell实例
	// contains filtered or unexported fields
}

ApiSudo 定义命令的结构体

func NewSudo added in v1.4.6

func NewSudo(password string) *ApiSudo

NewSudo 命令实例构造函数, 当不需要执行sudo命令的时候直接传入任意字符串给password即可

@Description:
@param password 主机密码
@return *ApiSudo

func (*ApiSudo) Grep added in v1.5.8

func (api *ApiSudo) Grep(match string) *ApiSudo

Grep 方法用于在 ApiSudo 结构体的 Strings 字段中查找包含指定字符串的行。 它利用关联的 Grep 函数来执行查找操作,并更新 ApiSudo 结构体的字段以反映查找结果。 参数:

match - 要查找的字符串。

返回值:

*ApiSudo - 返回指向 ApiSudo 实例的指针,以便进行链式调用。

func (*ApiSudo) RunScriptSudo added in v1.7.0

func (api *ApiSudo) RunScriptSudo(command ...string)

RunScriptSudo 执行脚本命令

func (*ApiSudo) RunSudo added in v1.7.0

func (api *ApiSudo) RunSudo(command ...string)

RunSudo 执行超级用户命令

func (*ApiSudo) RunSudoList added in v1.7.7

func (api *ApiSudo) RunSudoList(cs []string)

RunSudoList 执行一系列sudo命令

func (*ApiSudo) RunSudoTimeout added in v1.8.5

func (api *ApiSudo) RunSudoTimeout(timeout time.Duration, command ...string) *ApiSudo

RunSudoTimeout 执行超级用户命令并设置超时时间

@Description: 为sudo命令添加超时控制
@receiver api
@param timeout 超时时间(秒)
@param command 需要执行的命令,例如 'apt', 'update',命令与选项可以分开传入
@return *ApiSudo

Jump to

Keyboard shortcuts

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