golang本地与远程主机命令执行工具插件库sake的使用

Golang本地与远程主机命令执行工具插件库sake的使用

什么是sake

sake是一个用于本地和远程主机的命令执行工具。你可以在sake.yaml文件中定义服务器和任务,然后在服务器上运行这些任务。

demo

主要特性

  • 任务、服务器和标签的自动补全
  • 通过SSH连接到服务器或Docker容器:sake ssh <server>
  • 列出服务器/任务:sake list servers|tasks
  • 以紧凑的表格格式呈现任务输出:sake run <task> --output table
  • 在首选编辑器中打开任务/服务器:sake edit task <task>
  • 导入其他sake.yaml配置文件

安装方法

sake支持Linux和Mac系统,可以通过以下方式安装:

使用cURL安装

curl -sfL https://raw.githubusercontent.com/alajmo/sake/main/install.sh | sh

使用Homebrew安装

brew tap alajmo/sake
brew install sake

使用Go安装

go install github.com/alajmo/sake@latest

从源码构建

需要Go 1.19或更高版本:

make build && ./dist/sake
# 构建所有目标平台(需要goreleaser CLI)
make build-all

使用示例

初始化sake配置

$ sake init

Initialized sake in /tmp/sake
- Created sake.yaml

Following servers were added to sake.yaml

 Server    | Host
-----------+---------
 localhost | 0.0.0.0

列出服务器和任务

# 列出所有服务器
$ sake list servers

 Server    | Host
-----------+---------
 localhost | 0.0.0.0

# 列出所有任务
$ sake list tasks

 Task | Description
------+-------------
 ping | Pong

运行任务

# 运行ping任务
$ sake run ping --all

TASK ping: Pong ************

0.0.0.0 | pong

# 并行计算每个服务器中的文件数量
$ sake exec --all --output table --strategy=free 'find . -type f | wc -l'

 Server    | Output
-----------+--------
 localhost | 1

完整示例demo

以下是一个完整的sake.yaml配置示例:

# sake.yaml 示例配置
servers:
  - name: localhost
    host: 0.0.0.0
    description: "Local development server"
    
  - name: remote-server
    host: example.com
    user: root
    port: 22
    description: "Production server"

tasks:
  - name: ping
    cmd: "echo pong"
    description: "Simple ping test"
    
  - name: disk-usage
    cmd: "df -h"
    description: "Check disk usage"
    
  - name: count-files
    cmd: "find . -type f | wc -l"
    description: "Count files in current directory"

文档资源

  • 示例文档
  • 配置参考
  • 命令参考
  • 开发文档
  • 变更日志

许可证

MIT License (MIT)

Copyright © 2022 Samir Alajmovic


更多关于golang本地与远程主机命令执行工具插件库sake的使用的实战教程也可以访问 https://www.itying.com/category-94-b0.html

1 回复

更多关于golang本地与远程主机命令执行工具插件库sake的使用的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


Sake - Golang本地与远程主机命令执行工具库

Sake 是一个用 Go 语言编写的工具库,用于在本地和远程主机上执行命令。它提供了简单易用的 API 来执行 shell 命令,并支持 SSH 连接远程主机执行命令。

安装

go get github.com/alexellis/sake

基本使用

1. 本地命令执行

package main

import (
	"fmt"
	"log"

	"github.com/alexellis/sake/pkg/exec"
)

func main() {
	// 执行本地命令
	cmd := exec.Command("ls", "-la")
	output, err := cmd.CombinedOutput()
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println(string(output))
}

2. 远程SSH命令执行

package main

import (
	"fmt"
	"log"

	"github.com/alexellis/sake/pkg/ssh"
)

func main() {
	// 配置SSH客户端
	config := &ssh.Config{
		Host:     "example.com",
		Port:     22,
		User:     "username",
		Password: "password", // 或者使用 KeyPath 指定私钥路径
		// KeyPath: "/path/to/private/key",
	}

	// 创建SSH客户端
	client, err := ssh.NewClient(config)
	if err != nil {
		log.Fatal(err)
	}
	defer client.Close()

	// 执行远程命令
	output, err := client.Run("ls -la")
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println(output)
}

高级功能

1. 批量执行命令

package main

import (
	"fmt"
	"log"

	"github.com/alexellis/sake/pkg/exec"
	"github.com/alexellis/sake/pkg/ssh"
)

func main() {
	// 定义多个主机
	hosts := []ssh.Config{
		{
			Host:     "server1.example.com",
			User:     "user1",
			Password: "pass1",
		},
		{
			Host:     "server2.example.com",
			User:     "user2",
			KeyPath:  "/path/to/key",
		},
	}

	// 并行在所有主机上执行命令
	results := make(chan string, len(hosts))
	for _, host := range hosts {
		go func(h ssh.Config) {
			client, err := ssh.NewClient(&h)
			if err != nil {
				results <- fmt.Sprintf("Error connecting to %s: %v", h.Host, err)
				return
			}
			defer client.Close()

			output, err := client.Run("uname -a")
			if err != nil {
				results <- fmt.Sprintf("Error on %s: %v", h.Host, err)
				return
			}

			results <- fmt.Sprintf("%s:\n%s", h.Host, output)
		}(host)
	}

	// 收集结果
	for i := 0; i < len(hosts); i++ {
		fmt.Println(<-results)
	}
}

2. 文件传输

package main

import (
	"log"

	"github.com/alexellis/sake/pkg/ssh"
)

func main() {
	config := &ssh.Config{
		Host:     "example.com",
		User:     "username",
		Password: "password",
	}

	client, err := ssh.NewClient(config)
	if err != nil {
		log.Fatal(err)
	}
	defer client.Close()

	// 上传文件
	err = client.Upload("/local/path/file.txt", "/remote/path/file.txt")
	if err != nil {
		log.Fatal(err)
	}

	// 下载文件
	err = client.Download("/remote/path/file.txt", "/local/path/downloaded.txt")
	if err != nil {
		log.Fatal(err)
	}
}

3. 交互式会话

package main

import (
	"log"
	"os"

	"github.com/alexellis/sake/pkg/ssh"
)

func main() {
	config := &ssh.Config{
		Host:     "example.com",
		User:     "username",
		Password: "password",
	}

	client, err := ssh.NewClient(config)
	if err != nil {
		log.Fatal(err)
	}
	defer client.Close()

	// 启动交互式shell
	err = client.Shell(os.Stdin, os.Stdout, os.Stderr)
	if err != nil {
		log.Fatal(err)
	}
}

最佳实践

  1. 错误处理:始终检查错误并适当处理
  2. 资源清理:确保关闭SSH连接
  3. 并发控制:当批量执行时,使用sync.WaitGroup或通道控制并发
  4. 安全:优先使用SSH密钥认证而非密码
  5. 超时设置:为长时间运行的命令设置超时
// 带超时的命令执行示例
output, err := client.RunWithTimeout("long-running-command", 30*time.Second)

Sake 是一个轻量级但功能强大的库,适合需要自动化执行本地和远程命令的场景。它的API设计简洁,易于集成到现有的Go应用程序中。

回到顶部