Simple SSH client

Example ssh client - have to be improved and moved to a repo

Connects to a remote site using ssh, run a command and print the results of the command

 

 1package main
 2
 3import (
 4        "fmt"
 5        "bytes"
 6        "golang.org/x/crypto/ssh"
 7        "io/ioutil"
 8)
 9
10func check(e error) {
11    if e != nil {
12        panic(e)
13    }
14}
15
16//e.g. output, err := remoteRun("root", "MY_IP", "PRIVATE_KEY", "ls")
17func remoteRun(user string, addr string, privateKey string, cmd string) (string, error) {
18    // privateKey could be read from a file, or retrieved from another storage
19    // source, such as the Secret Service / GNOME Keyring
20    key, err := ssh.ParsePrivateKey([]byte(privateKey))
21    if err != nil {
22        return "", err
23    }
24    // Authentication
25    config := &ssh.ClientConfig{
26        User: user,
27        Auth: []ssh.AuthMethod{
28            ssh.PublicKeys(key),
29        },
30        HostKeyCallback: ssh.InsecureIgnoreHostKey(),
31        //alternatively, you could use a password
32        /*
33            Auth: []ssh.AuthMethod{
34                ssh.Password("PASSWORD"),
35            },
36        */
37    }
38    // Connect
39    client, err := ssh.Dial("tcp", addr+":22", config)
40    if err != nil {
41        return "", err
42    }
43    // Create a session. It is one session per command.
44    session, err := client.NewSession()
45    if err != nil {
46        return "", err
47    }
48    defer session.Close()
49    var b bytes.Buffer  // import "bytes"
50    session.Stdout = &b // get output
51    // you can also pass what gets input to the stdin, allowing you to pipe
52     // content from client to server
53    //      session.Stdin = bytes.NewBufferString("My input")
54
55    // Finally, run the command
56    err = session.Run(cmd)
57    return b.String(), err
58}
59
60func main() {
61dat, err := ioutil.ReadFile("/home/user1/.ssh/id_rsa")
62check(err)
63
64fmt.Printf(remoteRun("cato", "192.168.1.10", string(dat), "ls -la"))
65}