zyguan
11/15/2014 - 4:35 AM

Go lang SSH connection

Go lang SSH connection

package main

import (
  "bytes"
  "code.google.com/p/go.crypto/ssh"
  "fmt"
  "io/ioutil"
  "os"
)

func main() {
  pk, _ := ioutil.ReadFile(os.Getenv("HOME") + "/.ssh/id_rsa")
  signer, err := ssh.ParsePrivateKey(pk)

  if err != nil {
    panic(err)
  }

  config := &ssh.ClientConfig{
    User: "root",
    Auth: []ssh.AuthMethod{
      ssh.PublicKeys(signer),
    },
  }

  client, err := ssh.Dial("tcp", "hostname: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("ls"); err != nil {
    panic("Failed to run: " + err.Error())
  }
  fmt.Println(b.String())
}