Statistics
| Branch: | Tag: | Revision:

root / lib / ssh.py @ 8fd1bfa9

History | View | Annotate | Download (8.6 kB)

1
#
2
#
3

    
4
# Copyright (C) 2006, 2007, 2010, 2011 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
import re
30

    
31
from ganeti import utils
32
from ganeti import errors
33
from ganeti import constants
34
from ganeti import netutils
35
from ganeti import pathutils
36

    
37

    
38
def FormatParamikoFingerprint(fingerprint):
39
  """Format paramiko PKey fingerprint.
40

41
  @type fingerprint: str
42
  @param fingerprint: PKey fingerprint
43
  @return: The string hex representation of the fingerprint
44

45
  """
46
  assert len(fingerprint) % 2 == 0
47
  return ":".join(re.findall(r"..", fingerprint.lower()))
48

    
49

    
50
def GetUserFiles(user, mkdir=False):
51
  """Return the paths of a user's ssh files.
52

53
  The function will return a triplet (priv_key_path, pub_key_path,
54
  auth_key_path) that are used for ssh authentication. Currently, the
55
  keys used are DSA keys, so this function will return:
56
  (~user/.ssh/id_dsa, ~user/.ssh/id_dsa.pub,
57
  ~user/.ssh/authorized_keys).
58

59
  If the optional parameter mkdir is True, the ssh directory will be
60
  created if it doesn't exist.
61

62
  Regardless of the mkdir parameters, the script will raise an error
63
  if ~user/.ssh is not a directory.
64

65
  """
66
  user_dir = utils.GetHomeDir(user)
67
  if not user_dir:
68
    raise errors.OpExecError("Cannot resolve home of user %s" % user)
69

    
70
  ssh_dir = utils.PathJoin(user_dir, ".ssh")
71
  if mkdir:
72
    utils.EnsureDirs([(ssh_dir, constants.SECURE_DIR_MODE)])
73
  elif not os.path.isdir(ssh_dir):
74
    raise errors.OpExecError("Path %s is not a directory" % ssh_dir)
75

    
76
  return [utils.PathJoin(ssh_dir, base)
77
          for base in ["id_dsa", "id_dsa.pub", "authorized_keys"]]
78

    
79

    
80
class SshRunner:
81
  """Wrapper for SSH commands.
82

83
  """
84
  def __init__(self, cluster_name, ipv6=False):
85
    """Initializes this class.
86

87
    @type cluster_name: str
88
    @param cluster_name: name of the cluster
89
    @type ipv6: bool
90
    @param ipv6: If true, force ssh to use IPv6 addresses only
91

92
    """
93
    self.cluster_name = cluster_name
94
    self.ipv6 = ipv6
95

    
96
  def _BuildSshOptions(self, batch, ask_key, use_cluster_key,
97
                       strict_host_check, private_key=None, quiet=True):
98
    """Builds a list with needed SSH options.
99

100
    @param batch: same as ssh's batch option
101
    @param ask_key: allows ssh to ask for key confirmation; this
102
        parameter conflicts with the batch one
103
    @param use_cluster_key: if True, use the cluster name as the
104
        HostKeyAlias name
105
    @param strict_host_check: this makes the host key checking strict
106
    @param private_key: use this private key instead of the default
107
    @param quiet: whether to enable -q to ssh
108

109
    @rtype: list
110
    @return: the list of options ready to use in L{utils.process.RunCmd}
111

112
    """
113
    options = [
114
      "-oEscapeChar=none",
115
      "-oHashKnownHosts=no",
116
      "-oGlobalKnownHostsFile=%s" % pathutils.SSH_KNOWN_HOSTS_FILE,
117
      "-oUserKnownHostsFile=/dev/null",
118
      "-oCheckHostIp=no",
119
      ]
120

    
121
    if use_cluster_key:
122
      options.append("-oHostKeyAlias=%s" % self.cluster_name)
123

    
124
    if quiet:
125
      options.append("-q")
126

    
127
    if private_key:
128
      options.append("-i%s" % private_key)
129

    
130
    # TODO: Too many boolean options, maybe convert them to more descriptive
131
    # constants.
132

    
133
    # Note: ask_key conflicts with batch mode
134
    if batch:
135
      if ask_key:
136
        raise errors.ProgrammerError("SSH call requested conflicting options")
137

    
138
      options.append("-oBatchMode=yes")
139

    
140
      if strict_host_check:
141
        options.append("-oStrictHostKeyChecking=yes")
142
      else:
143
        options.append("-oStrictHostKeyChecking=no")
144

    
145
    else:
146
      # non-batch mode
147

    
148
      if ask_key:
149
        options.append("-oStrictHostKeyChecking=ask")
150
      elif strict_host_check:
151
        options.append("-oStrictHostKeyChecking=yes")
152
      else:
153
        options.append("-oStrictHostKeyChecking=no")
154

    
155
    if self.ipv6:
156
      options.append("-6")
157

    
158
    return options
159

    
160
  def BuildCmd(self, hostname, user, command, batch=True, ask_key=False,
161
               tty=False, use_cluster_key=True, strict_host_check=True,
162
               private_key=None, quiet=True):
163
    """Build an ssh command to execute a command on a remote node.
164

165
    @param hostname: the target host, string
166
    @param user: user to auth as
167
    @param command: the command
168
    @param batch: if true, ssh will run in batch mode with no prompting
169
    @param ask_key: if true, ssh will run with
170
        StrictHostKeyChecking=ask, so that we can connect to an
171
        unknown host (not valid in batch mode)
172
    @param use_cluster_key: whether to expect and use the
173
        cluster-global SSH key
174
    @param strict_host_check: whether to check the host's SSH key at all
175
    @param private_key: use this private key instead of the default
176
    @param quiet: whether to enable -q to ssh
177

178
    @return: the ssh call to run 'command' on the remote host.
179

180
    """
181
    argv = [constants.SSH]
182
    argv.extend(self._BuildSshOptions(batch, ask_key, use_cluster_key,
183
                                      strict_host_check, private_key,
184
                                      quiet=quiet))
185
    if tty:
186
      argv.extend(["-t", "-t"])
187
    argv.extend(["%s@%s" % (user, hostname), command])
188
    return argv
189

    
190
  def Run(self, *args, **kwargs):
191
    """Runs a command on a remote node.
192

193
    This method has the same return value as `utils.RunCmd()`, which it
194
    uses to launch ssh.
195

196
    Args: see SshRunner.BuildCmd.
197

198
    @rtype: L{utils.process.RunResult}
199
    @return: the result as from L{utils.process.RunCmd()}
200

201
    """
202
    return utils.RunCmd(self.BuildCmd(*args, **kwargs))
203

    
204
  def CopyFileToNode(self, node, filename):
205
    """Copy a file to another node with scp.
206

207
    @param node: node in the cluster
208
    @param filename: absolute pathname of a local file
209

210
    @rtype: boolean
211
    @return: the success of the operation
212

213
    """
214
    if not os.path.isabs(filename):
215
      logging.error("File %s must be an absolute path", filename)
216
      return False
217

    
218
    if not os.path.isfile(filename):
219
      logging.error("File %s does not exist", filename)
220
      return False
221

    
222
    command = [constants.SCP, "-p"]
223
    command.extend(self._BuildSshOptions(True, False, True, True))
224
    command.append(filename)
225
    if netutils.IP6Address.IsValid(node):
226
      node = netutils.FormatAddress((node, None))
227

    
228
    command.append("%s:%s" % (node, filename))
229

    
230
    result = utils.RunCmd(command)
231

    
232
    if result.failed:
233
      logging.error("Copy to node %s failed (%s) error '%s',"
234
                    " command was '%s'",
235
                    node, result.fail_reason, result.output, result.cmd)
236

    
237
    return not result.failed
238

    
239
  def VerifyNodeHostname(self, node):
240
    """Verify hostname consistency via SSH.
241

242
    This functions connects via ssh to a node and compares the hostname
243
    reported by the node to the name with have (the one that we
244
    connected to).
245

246
    This is used to detect problems in ssh known_hosts files
247
    (conflicting known hosts) and inconsistencies between dns/hosts
248
    entries and local machine names
249

250
    @param node: nodename of a host to check; can be short or
251
        full qualified hostname
252

253
    @return: (success, detail), where:
254
        - success: True/False
255
        - detail: string with details
256

257
    """
258
    retval = self.Run(node, "root", "hostname --fqdn", quiet=False)
259

    
260
    if retval.failed:
261
      msg = "ssh problem"
262
      output = retval.output
263
      if output:
264
        msg += ": %s" % output
265
      else:
266
        msg += ": %s (no output)" % retval.fail_reason
267
      logging.error("Command %s failed: %s", retval.cmd, msg)
268
      return False, msg
269

    
270
    remotehostname = retval.stdout.strip()
271

    
272
    if not remotehostname or remotehostname != node:
273
      if node.startswith(remotehostname + "."):
274
        msg = "hostname not FQDN"
275
      else:
276
        msg = "hostname mismatch"
277
      return False, ("%s: expected %s but got %s" %
278
                     (msg, node, remotehostname))
279

    
280
    return True, "host matches"
281

    
282

    
283
def WriteKnownHostsFile(cfg, file_name):
284
  """Writes the cluster-wide equally known_hosts file.
285

286
  """
287
  utils.WriteFile(file_name, mode=0600,
288
                  data="%s ssh-rsa %s\n" % (cfg.GetClusterName(),
289
                                            cfg.GetHostKey()))