Statistics
| Branch: | Tag: | Revision:

root / lib / ssh.py @ c41eea6e

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

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

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

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

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

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

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

    
108
    return options
109

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

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

125
    @return: the ssh call to run 'command' on the remote host.
126

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

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

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

142
    Args: see SshRunner.BuildCmd.
143

144
    @rtype: L{utils.RunResult}
145
    @return: the result as from L{utils.RunCmd()}
146

147
    """
148
    return utils.RunCmd(self.BuildCmd(*args, **kwargs))
149

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

153
    @param node: node in the cluster
154
    @param filename: absolute pathname of a local file
155

156
    @rtype: boolean
157
    @return: the success of the operation
158

159
    """
160
    if not os.path.isabs(filename):
161
      logging.error("File %s must be an absolute path", filename)
162
      return False
163

    
164
    if not os.path.isfile(filename):
165
      logging.error("File %s does not exist", filename)
166
      return False
167

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

    
173
    result = utils.RunCmd(command)
174

    
175
    if result.failed:
176
      logging.error("Copy to node %s failed (%s) error %s,"
177
                    " command was %s",
178
                    node, result.fail_reason, result.output, result.cmd)
179

    
180
    return not result.failed
181

    
182
  def VerifyNodeHostname(self, node):
183
    """Verify hostname consistency via SSH.
184

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

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

193
    @param node: nodename of a host to check; can be short or
194
        full qualified hostname
195

196
    @return: (success, detail), where:
197
        - success: True/False
198
        - detail: string with details
199

200
    """
201
    retval = self.Run(node, 'root', 'hostname')
202

    
203
    if retval.failed:
204
      msg = "ssh problem"
205
      output = retval.output
206
      if output:
207
        msg += ": %s" % output
208
      return False, msg
209

    
210
    remotehostname = retval.stdout.strip()
211

    
212
    if not remotehostname or remotehostname != node:
213
      return False, "hostname mismatch, got %s" % remotehostname
214

    
215
    return True, "host matches"
216

    
217

    
218
def WriteKnownHostsFile(cfg, file_name):
219
  """Writes the cluster-wide equally known_hosts file.
220

221
  """
222
  utils.WriteFile(file_name, mode=0700,
223
                  data="%s ssh-rsa %s\n" % (cfg.GetClusterName(),
224
                                            cfg.GetHostKey()))