可以只起一个 ssh 链接,如果执行多条命令,可以开多个 session
package main
import (
    "fmt"
    "net"
    "strconv"
    "time"
    "golang.org/x/crypto/ssh"
)
const (
    defaultIP = "0.0.0.1"
    userName  = "xxx"
    userPwd   = "xxx"
)
func connector(user, password, host string, port int) (sshClient *ssh.Client, err error) {
    //auth := make([]ssh.AuthMethod, 0)
    var auth []ssh.AuthMethod
    auth = append(auth, ssh.Password(password))
    clientConfig := &ssh.ClientConfig{
        User:    user,
        Auth:    auth,
        Timeout: 30 * time.Second,
        HostKeyCallback: func(hostname string, remote net.Addr, key ssh.PublicKey) error {
            return nil
        },
    }
    addr := host + ":" + strconv.Itoa(port)
    sshClient, err = ssh.Dial("tcp", addr, clientConfig) // connect ssh
    if err != nil {
        return nil, err
    }
    return
}
func sshSession(conn *ssh.Client) (sshSession *ssh.Session, err error) {
    if sshSession, err = conn.NewSession(); err != nil {
        return nil, err
    }
    return
}
func run() {
    sshConnector, err := connector(userName, userPwd, defaultIP, 22)
    if err != nil {
        // handle this error
    }
    defer sshConnector.Close()
    session1, err := sshSession(sshConnector)
    if err != nil {
        // handle error
    }
    defer session1.Close()
    command1 := "ls"
    out, _ := session1.Output(command1)
    outString := string(out)
    // handle this output
    fmt.Println(outString)
    session2, err := sshSession(sshConnector)
    if err != nil {
        // handle error
    }
    defer session2.Close()
    command2 := "ls"
    out, _ = session2.Output(command2)
    outString = string(out)
    // handle this output
    fmt.Println(outString)
}