This repository has been archived by the owner on Sep 14, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
scp.go
72 lines (63 loc) · 1.49 KB
/
scp.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package ssh
import (
"bytes"
"context"
"fmt"
"io"
"strings"
"golang.org/x/crypto/ssh"
)
type AuthorizedKeyConfig struct {
PrivateKey []byte
User string
Addr string
AuthorizedKey []byte
}
// AddAuthorizedKey copies public key to remove machine the same as ssh-copy-id command.
func AddAuthorizedKey(ctx context.Context, cfg AuthorizedKeyConfig) error {
signer, err := ssh.ParsePrivateKey(cfg.PrivateKey)
if err != nil {
return err
}
conn, err := ssh.Dial("tcp", cfg.Addr, &ssh.ClientConfig{
User: cfg.User,
Auth: []ssh.AuthMethod{
ssh.PublicKeys(signer),
},
HostKeyCallback: ssh.InsecureIgnoreHostKey(),
})
if err != nil {
return err
}
go func() {
<-ctx.Done()
conn.Close()
}()
out, err := runCommand(conn, "cat ~/.ssh/authorized_keys", nil)
if err != nil {
return fmt.Errorf("catting authorized_keys: %s: %w", out, err)
}
// Check if key is not already added.
if strings.Contains(out, strings.TrimSpace(string(cfg.AuthorizedKey))) {
return nil
}
out, err = runCommand(conn, "cat >> ~/.ssh/authorized_keys", bytes.NewBuffer(cfg.AuthorizedKey))
if err != nil {
return fmt.Errorf("adding new key: %s: %w", out, err)
}
return nil
}
func runCommand(conn *ssh.Client, cmd string, in io.Reader) (string, error) {
sess, err := conn.NewSession()
if err != nil {
return "", err
}
defer sess.Close()
out := &bytes.Buffer{}
sess.Stdout = out
sess.Stdin = in
if err := sess.Run(cmd); err != nil {
return "", err
}
return out.String(), nil
}