Experiments on Golang Ssh Package

Golang is one of the best programming language in recent times which made most of the developers transform their development stream to it with all its capabilities (which i’m not gonna talk about it) .

From the day 1 of my journey towards Golang it was bit awesome starting from Hello World Program to the recent SSH package based program.Thanks to @Deva for all his guidance in making me solve the basic problems with the language.

As part of the Project which i’m doing Dockerstack there was a functionality which have to be written to execute commands on remote servers and then come the SSH Package ,though it took some time for it to understand but with all the availability of the online blog posts on how to use this package made me write my own way of implementation.

Reference Blog Posts

http://golang-basic.blogspot.in/2014/06/step-by-step-guide-to-ssh-using-go.html

Basic Program

package main

import (
 "bytes"
 "fmt"
 "golang.org/x/crypto/ssh"
 "log"
 "time"
)

var stdoutBuf bytes.Buffer

func main() {

 v := time.Now()

 fmt.Println("Execution started @:", &v)

 config := &ssh.ClientConfig{
 User: "vagrant",
 Auth: []ssh.AuthMethod{
 ssh.Password("vagrant"),
 },
 }

 conn, err := ssh.Dial("tcp", "172.27.4.178:22", config)
 if err != nil {
 log.Fatal(err)
 }

 session, err := conn.NewSession()
 if err != nil {
 log.Fatal(err)
 }

 defer session.Close()

 session.Stdout = &stdoutBuf

 if err := session.Run("whoami"); err != nil {
 log.Fatal(err)
 }

 fmt.Println(stdoutBuf.String())

 fmt.Println("Execution Time Took:", time.Since(v))

}

Expected Output

vagrant@dhcppc2:/vagrant/go-tutorials$ go run blog.go
Execution started @: 2015-08-27 14:16:16.433186309 +0000 UTC
vagrant
Execution Time Took: 359.647428ms

I just love the way how the time package shows me the time phrase to show the total execution time it took to execute the command on the remote server.

Will Update this post more when i see any new use case i come across.

Leave a comment