测试基础 goland ssh

沐芓李 · 2021年09月26日 · 1277 次阅读

使用 goland ssh 远程链接机器, 执行多条命令

可以只起一个 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)
}

如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!
暂无回复。
需要 登录 后方可回复, 如果你还没有账号请点击这里 注册