golang使用ssh包登录服务器

ssh包的代码在这里:
https://github.com/golang/crypto.git

不要使用go get,不要使用go get,不要使用go get,不要使用go get,不要使用go get.
git clone出来后,放到$GOPATH/src/golang.org/x/目录下面即可。

package main

import (
“bytes”
“golang.org/x/crypto/ssh”
“fmt”
)

func main() {
fmt.Println(“helloworld”)

// An SSH client is represented with a ClientConn. Currently only
// the "password" authentication method is supported.
//
// To authenticate with the remote server you must pass at least one
// implementation of AuthMethod via the Auth field in ClientConfig.
config := &ssh.ClientConfig{
    User: "jenkins",
    Auth: []ssh.AuthMethod{
        ssh.Password("654321"),
    },
}
client, err := ssh.Dial("tcp", "11.22.33.44:22", config)
if err != nil {
    panic("Failed to dial: " + err.Error())
}

// Each ClientConn can support multiple interactive sessions,
// represented by a Session.
session, err := client.NewSession()
if err != nil {
    panic("Failed to create session: " + err.Error())
}
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("/usr/bin/whoami"); err != nil {
    panic("Failed to run: " + err.Error())
}
fmt.Println(b.String())

}

    原文作者:中國壹石頭
    原文地址: https://www.jianshu.com/p/463b7a097dc9
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞