Created
July 18, 2014 03:32
-
-
Save domluna/fab150fc706e8126aab4 to your computer and use it in GitHub Desktop.
Playing around with ssh clients in Go
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"bytes" | |
"fmt" | |
"io/ioutil" | |
"net" | |
"os/user" | |
"time" | |
"code.google.com/p/go.crypto/ssh" | |
) | |
func main() { | |
usr, err := user.Current() | |
if err != nil { | |
panic("failed to get current user") | |
} | |
pemBytes, err := ioutil.ReadFile(fmt.Sprintf("%s/.ssh/id_rsa", usr.HomeDir)) | |
if err != nil { | |
panic("failed to read private key") | |
} | |
private, err := ssh.ParsePrivateKey(pemBytes) | |
if err != nil { | |
panic("failed to parse private key") | |
} | |
config := &ssh.ClientConfig{ | |
User: "root", | |
Auth: []ssh.AuthMethod{ssh.PublicKeys(private)}, | |
} | |
conn, err := ssh.Dial("tcp", "107.170.143.188:22", config) | |
// conn, err := ssh.Dial("tcp", "104.131.225.249:22", config) | |
if err != nil { | |
panic("failed to connect via ssh to server") | |
} | |
session, err := conn.NewSession() | |
if err != nil { | |
panic("failed to start ssh session") | |
} | |
defer session.Close() | |
var b bytes.Buffer | |
session.Stdout = &b | |
err = session.Run("which ssh-keygen") | |
if err != nil { | |
panic("failed to do something with the output") | |
} | |
fmt.Printf("%s\n", b.Bytes()) | |
for { | |
_, err := net.DialTimeout("tcp", "104.131.225.249:22", time.Second*time.Duration(3)) | |
if err != nil { | |
fmt.Printf("timeout done retry ... \n") | |
time.Sleep(2 * time.Second) | |
} else { | |
fmt.Printf("found server\n") | |
break | |
} | |
} | |
// if err = session.Shell(); err != nil { | |
// panic("Error running the command") | |
// } | |
// Set up terminal modes | |
// modes := ssh.TerminalModes{ | |
// ssh.ECHO: 0, // disable echoing | |
// ssh.TTY_OP_ISPEED: 14400, // input speed = 14.4kbaud | |
// ssh.TTY_OP_OSPEED: 14400, // output speed = 14.4kbaud | |
// } | |
// // Request pseudo terminal | |
// if err := session.RequestPty("xterm", 80, 40, modes); err != nil { | |
// log.Fatalf("request for pseudo terminal failed: %s", err) | |
// } | |
// // Start remote shell | |
// if err := session.Shell(); err != nil { | |
// log.Fatalf("failed to start shell: %s", err) | |
// } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment