/
ssh.go
185 lines (160 loc) · 5.75 KB
/
ssh.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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
/*
* This file is part of the KubeVirt project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Copyright 2021 Red Hat, Inc.
*
*/
package ssh
import (
"fmt"
"os"
"path/filepath"
"github.com/golang/glog"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
"k8s.io/client-go/tools/clientcmd"
"kubevirt.io/kubevirt/pkg/virtctl/templates"
)
const (
portFlag, portFlagShort = "port", "p"
wrapLocalSSHFlag = "local-ssh"
usernameFlag, usernameFlagShort = "username", "l"
IdentityFilePathFlag, identityFilePathFlagShort = "identity-file", "i"
knownHostsFilePathFlag = "known-hosts"
commandToExecute, commandToExecuteShort = "command", "c"
additionalOpts, additionalOptsShort = "local-ssh-opts", "t"
)
func NewCommand(clientConfig clientcmd.ClientConfig) *cobra.Command {
c := &SSH{
clientConfig: clientConfig,
options: DefaultSSHOptions(),
}
cmd := &cobra.Command{
Use: "ssh (VM|VMI)",
Short: "Open a SSH connection to a virtual machine instance.",
Example: usage(),
Args: templates.ExactArgs("ssh", 1),
RunE: func(cmd *cobra.Command, args []string) error {
return c.Run(cmd, args)
},
}
AddCommandlineArgs(cmd.Flags(), &c.options)
cmd.Flags().StringVarP(&c.command, commandToExecute, commandToExecuteShort, c.command,
fmt.Sprintf(`--%s='ls /': Specify a command to execute in the VM`, commandToExecute))
cmd.SetUsageTemplate(templates.UsageTemplate())
return cmd
}
func AddCommandlineArgs(flagset *pflag.FlagSet, opts *SSHOptions) {
flagset.StringVarP(&opts.SSHUsername, usernameFlag, usernameFlagShort, opts.SSHUsername,
fmt.Sprintf("--%s=%s: Set this to the user you want to open the SSH connection as; If unassigned, this will be empty and the SSH default will apply", usernameFlag, opts.SSHUsername))
flagset.StringVarP(&opts.IdentityFilePath, IdentityFilePathFlag, identityFilePathFlagShort, opts.IdentityFilePath,
fmt.Sprintf("--%s=/home/jdoe/.ssh/id_rsa: Set the path to a private key used for authenticating to the server; If not provided, the client will try to use the local ssh-agent at $SSH_AUTH_SOCK", IdentityFilePathFlag))
flagset.StringVar(&opts.KnownHostsFilePath, knownHostsFilePathFlag, opts.KnownHostsFilePathDefault,
fmt.Sprintf("--%s=/home/jdoe/.ssh/kubevirt_known_hosts: Set the path to the known_hosts file.", knownHostsFilePathFlag))
flagset.IntVarP(&opts.SSHPort, portFlag, portFlagShort, opts.SSHPort,
fmt.Sprintf(`--%s=22: Specify a port on the VM to send SSH traffic to`, portFlag))
addAdditionalCommandlineArgs(flagset, opts)
}
func DefaultSSHOptions() SSHOptions {
homeDir, err := os.UserHomeDir()
if err != nil {
glog.Warningf("failed to determine user home directory: %v", err)
}
options := SSHOptions{
SSHPort: 22,
SSHUsername: defaultUsername(),
IdentityFilePath: filepath.Join(homeDir, ".ssh", "id_rsa"),
IdentityFilePathProvided: false,
KnownHostsFilePath: "",
KnownHostsFilePathDefault: "",
AdditionalSSHLocalOptions: []string{},
WrapLocalSSH: wrapLocalSSHDefault,
LocalClientName: "ssh",
}
if len(homeDir) > 0 {
options.KnownHostsFilePathDefault = filepath.Join(homeDir, ".ssh", "kubevirt_known_hosts")
}
return options
}
type SSH struct {
clientConfig clientcmd.ClientConfig
options SSHOptions
command string
}
type SSHOptions struct {
SSHPort int
SSHUsername string
IdentityFilePath string
IdentityFilePathProvided bool
KnownHostsFilePath string
KnownHostsFilePathDefault string
AdditionalSSHLocalOptions []string
WrapLocalSSH bool
LocalClientName string
}
func (o *SSH) Run(cmd *cobra.Command, args []string) error {
kind, namespace, name, err := PrepareCommand(cmd, o.clientConfig, &o.options, args)
if err != nil {
return err
}
if o.options.WrapLocalSSH {
clientArgs := o.buildSSHTarget(kind, namespace, name)
return RunLocalClient(kind, namespace, name, &o.options, clientArgs)
}
return o.nativeSSH(kind, namespace, name)
}
func PrepareCommand(cmd *cobra.Command, clientConfig clientcmd.ClientConfig, opts *SSHOptions, args []string) (kind, namespace, name string, err error) {
opts.IdentityFilePathProvided = cmd.Flags().Changed(IdentityFilePathFlag)
var targetUsername string
kind, namespace, name, targetUsername, err = templates.ParseSSHTarget(args[0])
if err != nil {
return
}
if len(namespace) < 1 {
namespace, _, err = clientConfig.Namespace()
if err != nil {
return
}
}
if len(targetUsername) > 0 {
opts.SSHUsername = targetUsername
}
return
}
func usage() string {
return fmt.Sprintf(` # Connect to 'testvmi':
{{ProgramName}} ssh jdoe@testvmi [--%s]
# Connect to 'testvm' in 'mynamespace' namespace
{{ProgramName}} ssh jdoe@vm/testvm.mynamespace [--%s]
# Specify a username and namespace:
{{ProgramName}} ssh --namespace=mynamespace --%s=jdoe testvmi`,
IdentityFilePathFlag,
IdentityFilePathFlag,
usernameFlag,
) + additionalUsage()
}
func defaultUsername() string {
vars := []string{
"USER", // linux
"USERNAME", // linux, windows
"LOGNAME", // linux
}
for _, env := range vars {
if v := os.Getenv(env); v != "" {
return v
}
}
return ""
}