golang - ssh tool

ssh 小工具

Why

之前做的 api 文档工具,因为 jekins 没有做脚本上的操作,只是单纯的复制.所以每次更新都有手动上去执行文档生成的命令

How

通过用户名密码,建立 ssh 连接.
执行一串命令,获取输出看是否执行成功

Code

package main

import (
"bytes"
"fmt"
"log"

"golang.org/x/crypto/ssh"
)

func main() {
// var hostKey ssh.PublicKey
config := &ssh.ClientConfig{
User: "username",
Auth: []ssh.AuthMethod{
ssh.Password("password"),
},
HostKeyCallback: ssh.InsecureIgnoreHostKey(),
}

client, err := ssh.Dial("tcp", "ip:22", config)
if err != nil {
log.Fatal("Failed to dial: ", err)
}
session, err := client.NewSession()
if err != nil {
log.Fatal("Failed to create session: ", err)
}
defer session.Close()

// Once a Session is created, you can execute a single command on
// the remote side using the Run method.
var b bytes.Buffer
session.Stdout = &b
if err := session.Run("cd xxpath;pwd;npm run build;exit"); err != nil {
log.Fatal("Failed to run: " + err.Error())
}
fmt.Println(b.String())
}