go mod init fast
go get github.com/manifoldco/promptui
go run main.go
main.go脚本信息
package main
import (
"fmt"
"log"
"os/exec"
"strings"
"github.com/manifoldco/promptui"
)
func main() {
// 定义选择框的标签和选项
label := "Select an option:"
options := []string{"K8S", "MYSQL", "REDIS", "Exit"}
// 创建选择框模板
templates := &promptui.SelectTemplates{
Label: "{{.}}",
Active: "\U0001F600 {{. | green}}",
Inactive: " {{.}}",
Selected: "{{. | bold | green }}",
}
// 运行选择框
prompt := promptui.Select{
Label: label,
Items: options,
Templates: templates,
}
// 获取用户选择的索引
i, _, err := prompt.Run()
if err != nil {
log.Fatalf("Prompt failed %v\n", err)
}
fmt.Println(options[i])
// 根据用户选择执行相应操作
switch i {
case 0:
fmt.Println("You selected 【K8S】 Option")
exec_k8s()
case 1:
fmt.Println("You selected 【MYSQL】Option")
exec_mysql()
case 2:
fmt.Println("You selected 【REDIS】 Option")
case 4:
fmt.Println("Exiting...")
return
default:
fmt.Println("Invalid selection")
}
fmt.Println("Press Enter to exit...")
fmt.Scanln() // 等待用户按键,以便在终端查看输出
}
func exec_mysql() {
cmd := exec.Command("sh", "-c", "mysql -h 127.0.0.1 -u root -P 3306 -padmin_123 -e 'show databases'")
// 执行并捕获输出
output, err := cmd.CombinedOutput()
if err != nil {
fmt.Printf("执行失败: %v\n输出: %s", err, string(output))
return
}
// 处理结果(去除换行符)
result := strings.TrimSpace(string(output))
fmt.Println("查询结果:\n", result)
}
func exec_k8s() {
cmd := exec.Command("sh", "-c","kubectl get pod --kubeconfig /root/go/test/kubeconfig")
// 执行并捕获输出
output, err := cmd.CombinedOutput()
if err != nil {
fmt.Printf("执行失败: %v\n输出: %s", err, string(output))
return
}
// 处理结果(去除换行符)
result := strings.TrimSpace(string(output))
fmt.Println("查询结果:\n", result)
lines := strings.Split(result, "\n")
var podsName []string
for _, line := range lines[1:] {
fields := strings.Fields(line)
if len(fields) > 0 {
podsName = append(podsName, fields[0])
}
}
// 定义选择框的标签和选项
label := "选择POD信息:"
options := podsName
// 创建选择框模板
templates := &promptui.SelectTemplates{
Label: "{{.}}",
Active: "\U0001F600 {{. | green}}",
Inactive: " {{.}}",
Selected: "{{. | bold | green }}",
}
// 运行选择框
prompt := promptui.Select{
Label: label,
Items: options,
Templates: templates,
}
// 获取用户选择的索引
i, _, err := prompt.Run()
if err != nil {
log.Fatalf("Prompt failed %v\n", err)
}
fmt.Println("查询pod 结果:\n", podsName[i] )
}