root / lib / ssh.py @ 2d3ed64b
History | View | Annotate | Download (7.2 kB)
1 |
#
|
---|---|
2 |
#
|
3 |
|
4 |
# Copyright (C) 2006, 2007 Google Inc.
|
5 |
#
|
6 |
# This program is free software; you can redistribute it and/or modify
|
7 |
# it under the terms of the GNU General Public License as published by
|
8 |
# the Free Software Foundation; either version 2 of the License, or
|
9 |
# (at your option) any later version.
|
10 |
#
|
11 |
# This program is distributed in the hope that it will be useful, but
|
12 |
# WITHOUT ANY WARRANTY; without even the implied warranty of
|
13 |
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
14 |
# General Public License for more details.
|
15 |
#
|
16 |
# You should have received a copy of the GNU General Public License
|
17 |
# along with this program; if not, write to the Free Software
|
18 |
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
|
19 |
# 02110-1301, USA.
|
20 |
|
21 |
|
22 |
"""Module encapsulating ssh functionality.
|
23 |
|
24 |
"""
|
25 |
|
26 |
|
27 |
import os |
28 |
import logging |
29 |
|
30 |
from ganeti import utils |
31 |
from ganeti import errors |
32 |
from ganeti import constants |
33 |
|
34 |
|
35 |
def GetUserFiles(user, mkdir=False): |
36 |
"""Return the paths of a user's ssh files.
|
37 |
|
38 |
The function will return a triplet (priv_key_path, pub_key_path,
|
39 |
auth_key_path) that are used for ssh authentication. Currently, the
|
40 |
keys used are DSA keys, so this function will return:
|
41 |
(~user/.ssh/id_dsa, ~user/.ssh/id_dsa.pub,
|
42 |
~user/.ssh/authorized_keys).
|
43 |
|
44 |
If the optional parameter mkdir is True, the ssh directory will be
|
45 |
created if it doesn't exist.
|
46 |
|
47 |
Regardless of the mkdir parameters, the script will raise an error
|
48 |
if ~user/.ssh is not a directory.
|
49 |
|
50 |
"""
|
51 |
user_dir = utils.GetHomeDir(user) |
52 |
if not user_dir: |
53 |
raise errors.OpExecError("Cannot resolve home of user %s" % user) |
54 |
|
55 |
ssh_dir = os.path.join(user_dir, ".ssh")
|
56 |
if not os.path.lexists(ssh_dir): |
57 |
if mkdir:
|
58 |
try:
|
59 |
os.mkdir(ssh_dir, 0700)
|
60 |
except EnvironmentError, err: |
61 |
raise errors.OpExecError("Can't create .ssh dir for user %s: %s" % |
62 |
(user, str(err)))
|
63 |
elif not os.path.isdir(ssh_dir): |
64 |
raise errors.OpExecError("path ~%s/.ssh is not a directory" % user) |
65 |
|
66 |
return [os.path.join(ssh_dir, base)
|
67 |
for base in ["id_dsa", "id_dsa.pub", "authorized_keys"]] |
68 |
|
69 |
|
70 |
class SshRunner: |
71 |
"""Wrapper for SSH commands.
|
72 |
|
73 |
"""
|
74 |
def __init__(self, cluster_name): |
75 |
self.cluster_name = cluster_name
|
76 |
|
77 |
def _BuildSshOptions(self, batch, ask_key, use_cluster_key, |
78 |
strict_host_check): |
79 |
"""Builds a list with needed SSH options.
|
80 |
|
81 |
@param batch: same as ssh's batch option
|
82 |
@param ask_key: allows ssh to ask for key confirmation; this
|
83 |
parameter conflicts with the batch one
|
84 |
@param use_cluster_key: if True, use the cluster name as the
|
85 |
HostKeyAlias name
|
86 |
@param strict_host_check: this makes the host key checking strict
|
87 |
|
88 |
@rtype: list
|
89 |
@return: the list of options ready to use in L{utils.RunCmd}
|
90 |
|
91 |
"""
|
92 |
options = [ |
93 |
"-oEscapeChar=none",
|
94 |
"-oHashKnownHosts=no",
|
95 |
"-oGlobalKnownHostsFile=%s" % constants.SSH_KNOWN_HOSTS_FILE,
|
96 |
"-oUserKnownHostsFile=/dev/null",
|
97 |
] |
98 |
|
99 |
if use_cluster_key:
|
100 |
options.append("-oHostKeyAlias=%s" % self.cluster_name) |
101 |
|
102 |
# TODO: Too many boolean options, maybe convert them to more descriptive
|
103 |
# constants.
|
104 |
|
105 |
# Note: ask_key conflicts with batch mode
|
106 |
if batch:
|
107 |
if ask_key:
|
108 |
raise errors.ProgrammerError("SSH call requested conflicting options") |
109 |
|
110 |
options.append("-oBatchMode=yes")
|
111 |
|
112 |
if strict_host_check:
|
113 |
options.append("-oStrictHostKeyChecking=yes")
|
114 |
else:
|
115 |
options.append("-oStrictHostKeyChecking=no")
|
116 |
|
117 |
elif ask_key:
|
118 |
options.extend([ |
119 |
"-oStrictHostKeyChecking=ask",
|
120 |
]) |
121 |
|
122 |
return options
|
123 |
|
124 |
def BuildCmd(self, hostname, user, command, batch=True, ask_key=False, |
125 |
tty=False, use_cluster_key=True, strict_host_check=True): |
126 |
"""Build an ssh command to execute a command on a remote node.
|
127 |
|
128 |
@param hostname: the target host, string
|
129 |
@param user: user to auth as
|
130 |
@param command: the command
|
131 |
@param batch: if true, ssh will run in batch mode with no prompting
|
132 |
@param ask_key: if true, ssh will run with
|
133 |
StrictHostKeyChecking=ask, so that we can connect to an
|
134 |
unknown host (not valid in batch mode)
|
135 |
@param use_cluster_key: whether to expect and use the
|
136 |
cluster-global SSH key
|
137 |
@param strict_host_check: whether to check the host's SSH key at all
|
138 |
|
139 |
@return: the ssh call to run 'command' on the remote host.
|
140 |
|
141 |
"""
|
142 |
argv = [constants.SSH, "-q"]
|
143 |
argv.extend(self._BuildSshOptions(batch, ask_key, use_cluster_key,
|
144 |
strict_host_check)) |
145 |
if tty:
|
146 |
argv.append("-t")
|
147 |
argv.extend(["%s@%s" % (user, hostname), command])
|
148 |
return argv
|
149 |
|
150 |
def Run(self, *args, **kwargs): |
151 |
"""Runs a command on a remote node.
|
152 |
|
153 |
This method has the same return value as `utils.RunCmd()`, which it
|
154 |
uses to launch ssh.
|
155 |
|
156 |
Args: see SshRunner.BuildCmd.
|
157 |
|
158 |
@rtype: L{utils.RunResult}
|
159 |
@return: the result as from L{utils.RunCmd()}
|
160 |
|
161 |
"""
|
162 |
return utils.RunCmd(self.BuildCmd(*args, **kwargs)) |
163 |
|
164 |
def CopyFileToNode(self, node, filename): |
165 |
"""Copy a file to another node with scp.
|
166 |
|
167 |
@param node: node in the cluster
|
168 |
@param filename: absolute pathname of a local file
|
169 |
|
170 |
@rtype: boolean
|
171 |
@return: the success of the operation
|
172 |
|
173 |
"""
|
174 |
if not os.path.isabs(filename): |
175 |
logging.error("File %s must be an absolute path", filename)
|
176 |
return False |
177 |
|
178 |
if not os.path.isfile(filename): |
179 |
logging.error("File %s does not exist", filename)
|
180 |
return False |
181 |
|
182 |
command = [constants.SCP, "-q", "-p"] |
183 |
command.extend(self._BuildSshOptions(True, False, True, True)) |
184 |
command.append(filename) |
185 |
command.append("%s:%s" % (node, filename))
|
186 |
|
187 |
result = utils.RunCmd(command) |
188 |
|
189 |
if result.failed:
|
190 |
logging.error("Copy to node %s failed (%s) error %s,"
|
191 |
" command was %s",
|
192 |
node, result.fail_reason, result.output, result.cmd) |
193 |
|
194 |
return not result.failed |
195 |
|
196 |
def VerifyNodeHostname(self, node): |
197 |
"""Verify hostname consistency via SSH.
|
198 |
|
199 |
This functions connects via ssh to a node and compares the hostname
|
200 |
reported by the node to the name with have (the one that we
|
201 |
connected to).
|
202 |
|
203 |
This is used to detect problems in ssh known_hosts files
|
204 |
(conflicting known hosts) and inconsistencies between dns/hosts
|
205 |
entries and local machine names
|
206 |
|
207 |
@param node: nodename of a host to check; can be short or
|
208 |
full qualified hostname
|
209 |
|
210 |
@return: (success, detail), where:
|
211 |
- success: True/False
|
212 |
- detail: string with details
|
213 |
|
214 |
"""
|
215 |
retval = self.Run(node, 'root', 'hostname') |
216 |
|
217 |
if retval.failed:
|
218 |
msg = "ssh problem"
|
219 |
output = retval.output |
220 |
if output:
|
221 |
msg += ": %s" % output
|
222 |
else:
|
223 |
msg += ": %s (no output)" % retval.fail_reason
|
224 |
logging.error("Command %s failed: %s" % (retval.cmd, msg))
|
225 |
return False, msg |
226 |
|
227 |
remotehostname = retval.stdout.strip() |
228 |
|
229 |
if not remotehostname or remotehostname != node: |
230 |
return False, "hostname mismatch, got %s" % remotehostname |
231 |
|
232 |
return True, "host matches" |
233 |
|
234 |
|
235 |
def WriteKnownHostsFile(cfg, file_name): |
236 |
"""Writes the cluster-wide equally known_hosts file.
|
237 |
|
238 |
"""
|
239 |
utils.WriteFile(file_name, mode=0600,
|
240 |
data="%s ssh-rsa %s\n" % (cfg.GetClusterName(),
|
241 |
cfg.GetHostKey())) |