| 1 | package main |
| 2 | |
| 3 | import ( |
| 4 | "fmt" |
| 5 | "net" |
| 6 | "os" |
| 7 | "time" |
| 8 | |
| 9 | "golang.org/x/crypto/ssh" |
| 10 | ) |
| 11 | |
| 12 | type client struct { |
| 13 | Conn net.Conn |
| 14 | Config *ssh.ClientConfig |
| 15 | } |
| 16 | |
| 17 | func newClient(conn net.Conn, user string, key string) (*client, error) { |
| 18 | config, err := newConfig(user, key) |
| 19 | if err != nil { |
| 20 | return nil, fmt.Errorf("error getting config for native Go SSH: %s", err) |
| 21 | } |
| 22 | |
| 23 | return &client{ |
| 24 | Conn: conn, |
| 25 | Config: config, |
| 26 | }, nil |
| 27 | } |
| 28 | |
| 29 | func newConfig(user string, keyFile string) (*ssh.ClientConfig, error) { |
| 30 | key, err := os.ReadFile(keyFile) |
| 31 | if err != nil { |
| 32 | return nil, err |
| 33 | } |
| 34 | privateKey, err := ssh.ParsePrivateKey(key) |
| 35 | if err != nil { |
| 36 | return nil, err |
| 37 | } |
| 38 | return &ssh.ClientConfig{ |
| 39 | User: user, |
| 40 | Auth: []ssh.AuthMethod{ssh.PublicKeys(privateKey)}, |
| 41 | |
| 42 | HostKeyCallback: ssh.InsecureIgnoreHostKey(), |
| 43 | Timeout: time.Minute, |
| 44 | }, nil |
| 45 | } |
| 46 | |
| 47 | func (client *client) output(command string) (string, error) { |
| 48 | c, chans, reqs, err := ssh.NewClientConn(client.Conn, "", client.Config) |
| 49 | if err != nil { |
| 50 | return "", err |
| 51 | } |
| 52 | conn := ssh.NewClient(c, chans, reqs) |
| 53 | session, err := conn.NewSession() |
| 54 | if err != nil { |
| 55 | _ = conn.Close() |
| 56 | return "", err |
| 57 | } |
| 58 | defer conn.Close() |
| 59 | defer session.Close() |
| 60 | |
| 61 | output, err := session.CombinedOutput(command) |
| 62 | if err != nil { |
| 63 | return "", err |
| 64 | } |
| 65 | return string(output), nil |
| 66 | } |