-
Notifications
You must be signed in to change notification settings - Fork 311
/
ssh_add.go
71 lines (60 loc) · 1.46 KB
/
ssh_add.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
package ssh
import (
"context"
"fmt"
"os"
"os/exec"
"path/filepath"
"time"
"github.com/loft-sh/devpod/pkg/command"
"github.com/loft-sh/log"
"github.com/mitchellh/go-homedir"
"golang.org/x/crypto/ssh"
)
func AddPrivateKeysToAgent(ctx context.Context, log log.Logger) error {
if os.Getenv("SSH_AUTH_SOCK") == "" {
return fmt.Errorf("ssh-agent is not started")
} else if !command.Exists("ssh-add") {
return fmt.Errorf("ssh-add couldn't be found")
}
privateKeys, err := FindPrivateKeys()
if err != nil {
return err
}
for _, privateKey := range privateKeys {
timeoutCtx, cancel := context.WithTimeout(ctx, time.Second*2)
log.Debugf("Run ssh-add %s", privateKey)
out, err := exec.CommandContext(timeoutCtx, "ssh-add", privateKey).CombinedOutput()
cancel()
if err != nil {
log.Debugf("Error adding key %s to agent: %v", privateKey, command.WrapCommandError(out, err))
}
}
return nil
}
func FindPrivateKeys() ([]string, error) {
homeDir, err := homedir.Dir()
if err != nil {
return nil, err
}
sshDir := filepath.Join(homeDir, ".ssh")
entries, err := os.ReadDir(sshDir)
if err != nil {
return nil, err
}
privateKeys := []string{}
for _, entry := range entries {
if entry.IsDir() {
continue
}
keyPath := filepath.Join(sshDir, entry.Name())
out, err := os.ReadFile(keyPath)
if err == nil {
_, err = ssh.ParsePrivateKey(out)
if err == nil {
privateKeys = append(privateKeys, keyPath)
}
}
}
return privateKeys, nil
}