一款管理远程服务器的辅助工具

yc90s · 2017-12-07 12:56:53 · 1239 次点击 · 大约8小时之前 开始浏览    置顶
这是一个创建于 2017-12-07 12:56:53 的主题,其中的信息可能已经有所发展或是发生改变。

工具介绍

xpub是一款用来辅助管理远程服务器的工具,使用ssh连接

项目地址:https://gitee.com/1050676515/xpub

特性

  1. 可以同时管理多台服务器
  2. 可以同时在多台服务器批量执行命令
  3. 可以自定义命令,将一组命令的集合定义成一条命令
  4. 提供与远程服务器的交互式shell

目录说明

  1. config:用来存放配置文件
  2. src:src目录存放源码文件
  3. src/config目录:存放解析配置文件相关的代码
  4. src/sshhelprt目录:存放ssh连接与命令执行相关的代码
  5. src/xterm目录:获取输入相关的代码,提供类似于*nix终端的操作,支持自动补全、历史命令相关的输入操作

部分代码

type Server struct {
    config.Section
    *sshhelper.SSHClient
    addr        string
    commandsMap map[string]string
}

func NewServer(config config.Section) *Server {
    var cmdMap map[string]string
    cmdMap = make(map[string]string)
    for _, command := range config.Commands {
        cmdMap[command.Cmd] = command.Commandfile
    }

    var buf bytes.Buffer
    buf.WriteString(config.Host)
    buf.WriteString(":")
    buf.WriteString(config.Port)
    sshclient := sshhelper.NewSSHClient()

    return &Server{Section: config, commandsMap: cmdMap, addr: buf.String(), SSHClient: sshclient}
}

func (ctx *Server) Close() {
    ctx.SSHClient.Close()
}

func (ctx *Server) Connect() error {
    return ctx.SSHClient.Connect(ctx.addr, ctx.Username, ctx.Passwd)
}

func (ctx *Server) Active(xTerm *xterm.XTerm) {
    oldPrompt := xTerm.SetPrompt("[" + ctx.Username + "@" + ctx.Name + " ~]>>> ")
    defer xTerm.SetPrompt(oldPrompt)
ForEnd:
    for {
        line, err := xTerm.ReadLine()
        if err != nil {
            panic(err)
        }

        cmd := strings.ToLower(line)
        cmd = strings.TrimSpace(cmd)
        switch cmd {
        case "help":
            serverUsage()
        case "quit":
            break ForEnd
        case "shell":
            if err := ctx.StartShell(); err != nil {
                fmt.Println(err)
            }
        default:
            if err := ctx.Command(cmd); err != nil {
                fmt.Println(err)
            }
        }
    }
}

func (ctx *Server) Command(cmd string) error {
    if len(cmd) == 0 {
        return nil
    }
    if file, ok := ctx.commandsMap[cmd]; ok {
        return ctx.RunCommandFile(file)
    }
    return errors.New(cmd + " not exist.")
}

func serverUsage() {
    str := `Usage:
    shell:    start a interactive shell with the remote host
    help :    display this help
    quit :    go back to the last one     

Otherwise, You can enter the commands that you configure in your configuration file. Only this server will execute. 
`
    fmt.Println(str)
}

有疑问加站长微信联系(非本文作者)

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

1239 次点击  
加入收藏 微博
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传