Skip to content

Commit 854cb2b

Browse files
use ssh-agent to access stored keys
1 parent eb5283f commit 854cb2b

File tree

1 file changed

+9
-25
lines changed

1 file changed

+9
-25
lines changed

examples/main.go

+9-25
Original file line numberDiff line numberDiff line change
@@ -4,11 +4,13 @@ import (
44
"bytes"
55
"fmt"
66
"log"
7+
"net"
78
"os"
89

910
"github.com/84codes/sparoid.go"
1011
"github.com/joho/godotenv"
1112
"golang.org/x/crypto/ssh"
13+
"golang.org/x/crypto/ssh/agent"
1214
"golang.org/x/crypto/ssh/knownhosts"
1315
)
1416

@@ -23,45 +25,27 @@ func main() {
2325
if err != nil {
2426
log.Fatal("Auth failed", err)
2527
}
26-
//var hostKey ssh.PublicKey
27-
// An SSH client is represented with a ClientConn.
28-
//
29-
// To authenticate with the remote server you must pass at least one
30-
// implementation of AuthMethod via the Auth field in ClientConfig,
31-
// and provide a HostKeyCallback.
32-
key, err := os.ReadFile(fmt.Sprintf("%s/.ssh/id_ed25519", os.Getenv("HOME")))
33-
if err != nil {
34-
log.Fatal("Failed to load private key", err)
35-
}
3628

37-
signer, err := ssh.ParsePrivateKeyWithPassphrase(key, []byte(os.Getenv("SSH_PASS")))
29+
socket := os.Getenv("SSH_AUTH_SOCK")
30+
conn, err := net.Dial("unix", socket)
3831
if err != nil {
39-
log.Fatal("Failed to parse private key", err)
32+
log.Fatalf("Failed to open SSH_AUTH_SOCK: %v", err)
4033
}
4134

42-
publicKey, err := os.ReadFile(fmt.Sprintf("%s/.ssh/id_ed25519-cert.pub", os.Getenv("HOME")))
43-
if err != nil {
44-
log.Fatal("Failed to load public key", err)
45-
}
46-
pubKey, _, _, _, err := ssh.ParseAuthorizedKey(publicKey)
47-
if err != nil {
48-
log.Fatal("Failed to parse public key", err)
49-
}
50-
certSigner, err := ssh.NewCertSigner(pubKey.(*ssh.Certificate), signer)
51-
if err != nil {
52-
log.Fatalf("failed to create cert signer: %v", err)
53-
}
35+
agentClient := agent.NewClient(conn)
36+
5437
knownhostsCallback, err := knownhosts.New(fmt.Sprintf("%s/.ssh/known_hosts", os.Getenv("HOME")))
5538
if err != nil {
5639
log.Fatal("Failed to load known hosts", err)
5740
}
5841
config := &ssh.ClientConfig{
5942
User: "ubuntu",
6043
Auth: []ssh.AuthMethod{
61-
ssh.PublicKeys(certSigner),
44+
ssh.PublicKeysCallback(agentClient.Signers),
6245
},
6346
HostKeyCallback: knownhostsCallback,
6447
}
48+
// An SSH client is represented with a ClientConn.
6549
client, err := ssh.Dial("tcp", fmt.Sprintf("%s:22", hostname), config)
6650
if err != nil {
6751
log.Fatal("Failed to dial: ", err)

0 commit comments

Comments
 (0)