blob: 99f3e906fb110701d98dcc9b764cf8a5d356bf53 [file] [log] [blame]
Tim Windelschmidtb6308cd2023-10-10 21:19:03 +02001package main
2
3import (
4 "flag"
5 "fmt"
6
7 "golang.org/x/crypto/ssh"
8 "k8s.io/klog/v2"
9
10 "source.monogon.dev/cloud/shepherd/manager"
11)
12
13type sshConfig struct {
14 User string
15 Pass string
16 SSHKey manager.SSHKey
17}
18
19func (sc *sshConfig) check() error {
20 if sc.User == "" {
21 return fmt.Errorf("-ssh_user must be set")
22 }
23
24 if sc.Pass == "" && sc.SSHKey.KeyPersistPath == "" {
25 //TODO: The flag name -ssh_key_path could change, which would make this
26 // error very confusing.
27 return fmt.Errorf("-ssh_pass or -ssh_key_path must be set")
28 }
29
30 return nil
31}
32
33func (sc *sshConfig) RegisterFlags() {
34 flag.StringVar(&sc.User, "ssh_user", "", "SSH username to log into the machines")
35 flag.StringVar(&sc.Pass, "ssh_pass", "", "SSH password to log into the machines")
36 sc.SSHKey.RegisterFlags()
37}
38
39func (sc *sshConfig) NewClient() (*manager.PlainSSHClient, error) {
40 if err := sc.check(); err != nil {
41 return nil, err
42 }
43
44 c := manager.PlainSSHClient{
45 Username: sc.User,
46 }
47
48 switch {
49 case sc.Pass != "":
50 c.AuthMethod = ssh.Password(sc.Pass)
51 case sc.SSHKey.KeyPersistPath != "":
52 signer, err := sc.SSHKey.Signer()
53 if err != nil {
54 return nil, err
55 }
56
57 pubKey, err := sc.SSHKey.PublicKey()
58 if err != nil {
59 return nil, err
60 }
61
62 klog.Infof("Using ssh key auth with public key: %s", pubKey)
63
64 c.AuthMethod = ssh.PublicKeys(signer)
65 }
66 return &c, nil
67}