Statistics
| Branch: | Tag: | Revision:

root / lib / ssh.py @ 6605411d

History | View | Annotate | Download (6.6 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

    
29
from ganeti import logger
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
    options = [
80
      "-oEscapeChar=none",
81
      "-oHashKnownHosts=no",
82
      "-oGlobalKnownHostsFile=%s" % constants.SSH_KNOWN_HOSTS_FILE,
83
      "-oUserKnownHostsFile=/dev/null",
84
      ]
85

    
86
    if use_cluster_key:
87
      options.append("-oHostKeyAlias=%s" % self.cluster_name)
88

    
89
    # TODO: Too many boolean options, maybe convert them to more descriptive
90
    # constants.
91

    
92
    # Note: ask_key conflicts with batch mode
93
    if batch:
94
      if ask_key:
95
        raise errors.ProgrammerError("SSH call requested conflicting options")
96

    
97
      options.append("-oBatchMode=yes")
98

    
99
      if strict_host_check:
100
        options.append("-oStrictHostKeyChecking=yes")
101
      else:
102
        options.append("-oStrictHostKeyChecking=no")
103

    
104
    elif ask_key:
105
      options.extend([
106
        "-oStrictHostKeyChecking=ask",
107
        ])
108

    
109
    return options
110

    
111
  def BuildCmd(self, hostname, user, command, batch=True, ask_key=False,
112
               tty=False, use_cluster_key=True, strict_host_check=True):
113
    """Build an ssh command to execute a command on a remote node.
114

115
    Args:
116
      hostname: the target host, string
117
      user: user to auth as
118
      command: the command
119
      batch: if true, ssh will run in batch mode with no prompting
120
      ask_key: if true, ssh will run with StrictHostKeyChecking=ask, so that
121
               we can connect to an unknown host (not valid in batch mode)
122
      use_cluster_key: Whether to expect and use the cluster-global SSH key
123
      strict_host_check: Whether to check the host's SSH key at all
124

125
    Returns:
126
      The ssh call to run 'command' on the remote host.
127

128
    """
129
    argv = [constants.SSH, "-q"]
130
    argv.extend(self._BuildSshOptions(batch, ask_key, use_cluster_key,
131
                                      strict_host_check))
132
    if tty:
133
      argv.append("-t")
134
    argv.extend(["%s@%s" % (user, hostname), command])
135
    return argv
136

    
137
  def Run(self, *args, **kwargs):
138
    """Runs a command on a remote node.
139

140
    This method has the same return value as `utils.RunCmd()`, which it
141
    uses to launch ssh.
142

143
    Args:
144
      See SshRunner.BuildCmd.
145

146
    Returns:
147
      `utils.RunResult` like `utils.RunCmd()`
148

149
    """
150
    return utils.RunCmd(self.BuildCmd(*args, **kwargs))
151

    
152
  def CopyFileToNode(self, node, filename):
153
    """Copy a file to another node with scp.
154

155
    Args:
156
      node: node in the cluster
157
      filename: absolute pathname of a local file
158

159
    Returns:
160
      success: True/False
161

162
    """
163
    if not os.path.isabs(filename):
164
      logger.Error("file %s must be an absolute path" % (filename))
165
      return False
166

    
167
    if not os.path.isfile(filename):
168
      logger.Error("file %s does not exist" % (filename))
169
      return False
170

    
171
    command = [constants.SCP, "-q", "-p"]
172
    command.extend(self._BuildSshOptions(True, False, True, True))
173
    command.append(filename)
174
    command.append("%s:%s" % (node, filename))
175

    
176
    result = utils.RunCmd(command)
177

    
178
    if result.failed:
179
      logger.Error("copy to node %s failed (%s) error %s,"
180
                   " command was %s" %
181
                   (node, result.fail_reason, result.output, result.cmd))
182

    
183
    return not result.failed
184

    
185
  def VerifyNodeHostname(self, node):
186
    """Verify hostname consistency via SSH.
187

188
    This functions connects via ssh to a node and compares the hostname
189
    reported by the node to the name with have (the one that we
190
    connected to).
191

192
    This is used to detect problems in ssh known_hosts files
193
    (conflicting known hosts) and incosistencies between dns/hosts
194
    entries and local machine names
195

196
    Args:
197
      node: nodename of a host to check. can be short or full qualified hostname
198

199
    Returns:
200
      (success, detail)
201
      where
202
        success: True/False
203
        detail: String with details
204

205
    """
206
    retval = self.Run(node, 'root', 'hostname')
207

    
208
    if retval.failed:
209
      msg = "ssh problem"
210
      output = retval.output
211
      if output:
212
        msg += ": %s" % output
213
      return False, msg
214

    
215
    remotehostname = retval.stdout.strip()
216

    
217
    if not remotehostname or remotehostname != node:
218
      return False, "hostname mismatch, got %s" % remotehostname
219

    
220
    return True, "host matches"
221

    
222

    
223
def WriteKnownHostsFile(cfg, file_name):
224
  """Writes the cluster-wide equally known_hosts file.
225

226
  """
227
  utils.WriteFile(file_name, mode=0700,
228
                  data="%s ssh-rsa %s\n" % (cfg.GetClusterName(),
229
                                            cfg.GetHostKey()))