标签归档: golang

一个Go语言SSH客户端的例子

an example of ssh client in golang

Google搜了好几个例子都用不了,好像是因为ssh库更新了,没办法只好自己摸索了。

这里用的是RSA Private Key来连接,要改成用密码连接也很容易。

参考文档:https://godoc.org/code.google.com/p/go.crypto/ssh

// 运行前得先安装ssh支持库: go get code.google.com/p/go.crypto/ssh

package main

import (
    "code.google.com/p/go.crypto/ssh"
    "io"
    "log"
)

var (
    pemBytes = `-----BEGIN RSA PRIVATE KEY-----
.......
.......
.......
-----END RSA PRIVATE KEY-----`
)

type keychain struct {
    signer ssh.Signer
}

func (k *keychain) Key(i int) (ssh.PublicKey, error) {
    if i != 0 {
        return nil, nil
    }
    pk := k.signer.PublicKey()
    return pk, nil
}

func (k *keychain) Sign(i int, rand io.Reader, data []byte) (sig []byte, err error) {
    return k.signer.Sign(rand, data)
}

func main() {
    signer, err := ssh.ParsePrivateKey([]byte(pemBytes))
    if err != nil {
        panic(err)
    }

    clientKey := &keychain{signer}

    config := &ssh.ClientConfig{
        User: "Hessian",
        Auth: []ssh.ClientAuth{
            ssh.ClientAuthKeyring(clientKey),
        },
    }
    c, err := ssh.Dial("tcp", "YOUR_HOST:22", config)
    if err != nil {
        log.Println("unable to dial remote side:", err)
    }
    defer c.Close()

    // Create a session
    session, err := c.NewSession()
    if err != nil {
        log.Fatalf("unable to create session: %s", err)
    }
    defer session.Close()

    b, err := session.Output("ls -l")
    if err != nil {
        log.Fatalf("failed to execute: %s", err)
    }
    log.Println("Output: ", string(b))

    return
}

Read: 2137