-
Notifications
You must be signed in to change notification settings - Fork 301
/
ssh_client.go
89 lines (74 loc) · 1.92 KB
/
ssh_client.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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
package helper
import (
"context"
"os"
command2 "github.com/loft-sh/devpod/pkg/command"
"github.com/pkg/errors"
"github.com/spf13/cobra"
"golang.org/x/crypto/ssh"
)
type SSHClient struct {
Address string
KeyFile string
User string
}
// NewSSHClientCmd creates a new ssh command
func NewSSHClientCmd() *cobra.Command {
cmd := &SSHClient{}
sshCmd := &cobra.Command{
Use: "ssh-client",
Short: "Starts a new ssh client session",
RunE: func(_ *cobra.Command, args []string) error {
return cmd.Run(context.Background(), args)
},
}
sshCmd.Flags().StringVar(&cmd.KeyFile, "key-file", "", "SSH Key file to use")
sshCmd.Flags().StringVar(&cmd.Address, "address", "", "Address to connect to")
sshCmd.Flags().StringVar(&cmd.User, "user", "root", "User to connect as")
_ = sshCmd.MarkFlagRequired("address")
return sshCmd
}
func (cmd *SSHClient) Run(ctx context.Context, args []string) error {
sshConfig, err := cmd.getConfig()
if err != nil {
return err
}
sshClient, err := ssh.Dial("tcp", cmd.Address, sshConfig)
if err != nil {
return err
}
defer sshClient.Close()
sess, err := sshClient.NewSession()
if err != nil {
return err
}
defer sess.Close()
sess.Stdin = os.Stdin
sess.Stdout = os.Stdout
sess.Stderr = os.Stderr
err = sess.Run(command2.Quote(args))
if err != nil {
return err
}
return nil
}
func (cmd *SSHClient) getConfig() (*ssh.ClientConfig, error) {
clientConfig := &ssh.ClientConfig{
User: cmd.User,
Auth: []ssh.AuthMethod{},
HostKeyCallback: ssh.InsecureIgnoreHostKey(),
}
// key file authentication?
if cmd.KeyFile != "" {
out, err := os.ReadFile(cmd.KeyFile)
if err != nil {
return nil, errors.Wrap(err, "read private ssh key")
}
signer, err := ssh.ParsePrivateKey(out)
if err != nil {
return nil, errors.Wrap(err, "parse private key")
}
clientConfig.Auth = append(clientConfig.Auth, ssh.PublicKeys(signer))
}
return clientConfig, nil
}