Skip to content

Instantly share code, notes, and snippets.

@andrielfn
Created November 15, 2014 04:35
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save andrielfn/7aa336f9b6dc9e2a5dac to your computer and use it in GitHub Desktop.
Save andrielfn/7aa336f9b6dc9e2a5dac to your computer and use it in GitHub Desktop.
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())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment