Statistics
| Branch: | Tag: | Revision:

root / lib / ssh.py @ bf75f132

History | View | Annotate | Download (7.1 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 utils
30
from ganeti import errors
31
from ganeti import constants
32

    
33

    
34
def GetUserFiles(user, mkdir=False):
35
  """Return the paths of a user's ssh files.
36

37
  The function will return a triplet (priv_key_path, pub_key_path,
38
  auth_key_path) that are used for ssh authentication. Currently, the
39
  keys used are DSA keys, so this function will return:
40
  (~user/.ssh/id_dsa, ~user/.ssh/id_dsa.pub,
41
  ~user/.ssh/authorized_keys).
42

43
  If the optional parameter mkdir is True, the ssh directory will be
44
  created if it doesn't exist.
45

46
  Regardless of the mkdir parameters, the script will raise an error
47
  if ~user/.ssh is not a directory.
48

49
  """
50
  user_dir = utils.GetHomeDir(user)
51
  if not user_dir:
52
    raise errors.OpExecError("Cannot resolve home of user %s" % user)
53

    
54
  ssh_dir = os.path.join(user_dir, ".ssh")
55
  if not os.path.lexists(ssh_dir):
56
    if mkdir:
57
      try:
58
        os.mkdir(ssh_dir, 0700)
59
      except EnvironmentError, err:
60
        raise errors.OpExecError("Can't create .ssh dir for user %s: %s" %
61
                                 (user, str(err)))
62
  elif not os.path.isdir(ssh_dir):
63
    raise errors.OpExecError("path ~%s/.ssh is not a directory" % user)
64

    
65
  return [os.path.join(ssh_dir, base)
66
          for base in ["id_dsa", "id_dsa.pub", "authorized_keys"]]
67

    
68

    
69
class SshRunner:
70
  """Wrapper for SSH commands.
71

72
  """
73
  def __init__(self, cluster_name):
74
    self.cluster_name = cluster_name
75

    
76
  def _BuildSshOptions(self, batch, ask_key, use_cluster_key,
77
                       strict_host_check):
78
    """Builds a list with needed SSH options.
79

80
    @param batch: same as ssh's batch option
81
    @param ask_key: allows ssh to ask for key confirmation; this
82
        parameter conflicts with the batch one
83
    @param use_cluster_key: if True, use the cluster name as the
84
        HostKeyAlias name
85
    @param strict_host_check: this makes the host key checking strict
86

87
    @rtype: list
88
    @return: the list of options ready to use in L{utils.RunCmd}
89

90
    """
91
    options = [
92
      "-oEscapeChar=none",
93
      "-oHashKnownHosts=no",
94
      "-oGlobalKnownHostsFile=%s" % constants.SSH_KNOWN_HOSTS_FILE,
95
      "-oUserKnownHostsFile=/dev/null",
96
      ]
97

    
98
    if use_cluster_key:
99
      options.append("-oHostKeyAlias=%s" % self.cluster_name)
100

    
101
    # TODO: Too many boolean options, maybe convert them to more descriptive
102
    # constants.
103

    
104
    # Note: ask_key conflicts with batch mode
105
    if batch:
106
      if ask_key:
107
        raise errors.ProgrammerError("SSH call requested conflicting options")
108

    
109
      options.append("-oBatchMode=yes")
110

    
111
      if strict_host_check:
112
        options.append("-oStrictHostKeyChecking=yes")
113
      else:
114
        options.append("-oStrictHostKeyChecking=no")
115

    
116
    elif ask_key:
117
      options.extend([
118
        "-oStrictHostKeyChecking=ask",
119
        ])
120

    
121
    return options
122

    
123
  def BuildCmd(self, hostname, user, command, batch=True, ask_key=False,
124
               tty=False, use_cluster_key=True, strict_host_check=True):
125
    """Build an ssh command to execute a command on a remote node.
126

127
    @param hostname: the target host, string
128
    @param user: user to auth as
129
    @param command: the command
130
    @param batch: if true, ssh will run in batch mode with no prompting
131
    @param ask_key: if true, ssh will run with
132
        StrictHostKeyChecking=ask, so that we can connect to an
133
        unknown host (not valid in batch mode)
134
    @param use_cluster_key: whether to expect and use the
135
        cluster-global SSH key
136
    @param strict_host_check: whether to check the host's SSH key at all
137

138
    @return: the ssh call to run 'command' on the remote host.
139

140
    """
141
    argv = [constants.SSH, "-q"]
142
    argv.extend(self._BuildSshOptions(batch, ask_key, use_cluster_key,
143
                                      strict_host_check))
144
    if tty:
145
      argv.append("-t")
146
    argv.extend(["%s@%s" % (user, hostname), command])
147
    return argv
148

    
149
  def Run(self, *args, **kwargs):
150
    """Runs a command on a remote node.
151

152
    This method has the same return value as `utils.RunCmd()`, which it
153
    uses to launch ssh.
154

155
    Args: see SshRunner.BuildCmd.
156

157
    @rtype: L{utils.RunResult}
158
    @return: the result as from L{utils.RunCmd()}
159

160
    """
161
    return utils.RunCmd(self.BuildCmd(*args, **kwargs))
162

    
163
  def CopyFileToNode(self, node, filename):
164
    """Copy a file to another node with scp.
165

166
    @param node: node in the cluster
167
    @param filename: absolute pathname of a local file
168

169
    @rtype: boolean
170
    @return: the success of the operation
171

172
    """
173
    if not os.path.isabs(filename):
174
      logging.error("File %s must be an absolute path", filename)
175
      return False
176

    
177
    if not os.path.isfile(filename):
178
      logging.error("File %s does not exist", filename)
179
      return False
180

    
181
    command = [constants.SCP, "-q", "-p"]
182
    command.extend(self._BuildSshOptions(True, False, True, True))
183
    command.append(filename)
184
    command.append("%s:%s" % (node, filename))
185

    
186
    result = utils.RunCmd(command)
187

    
188
    if result.failed:
189
      logging.error("Copy to node %s failed (%s) error %s,"
190
                    " command was %s",
191
                    node, result.fail_reason, result.output, result.cmd)
192

    
193
    return not result.failed
194

    
195
  def VerifyNodeHostname(self, node):
196
    """Verify hostname consistency via SSH.
197

198
    This functions connects via ssh to a node and compares the hostname
199
    reported by the node to the name with have (the one that we
200
    connected to).
201

202
    This is used to detect problems in ssh known_hosts files
203
    (conflicting known hosts) and incosistencies between dns/hosts
204
    entries and local machine names
205

206
    @param node: nodename of a host to check; can be short or
207
        full qualified hostname
208

209
    @return: (success, detail), where:
210
        - success: True/False
211
        - detail: string with details
212

213
    """
214
    retval = self.Run(node, 'root', 'hostname')
215

    
216
    if retval.failed:
217
      msg = "ssh problem"
218
      output = retval.output
219
      if output:
220
        msg += ": %s" % output
221
      return False, msg
222

    
223
    remotehostname = retval.stdout.strip()
224

    
225
    if not remotehostname or remotehostname != node:
226
      return False, "hostname mismatch, got %s" % remotehostname
227

    
228
    return True, "host matches"
229

    
230

    
231
def WriteKnownHostsFile(cfg, file_name):
232
  """Writes the cluster-wide equally known_hosts file.
233

234
  """
235
  utils.WriteFile(file_name, mode=0700,
236
                  data="%s ssh-rsa %s\n" % (cfg.GetClusterName(),
237
                                            cfg.GetHostKey()))