Statistics
| Branch: | Tag: | Revision:

root / lib / ssh.py @ f6d9f4c3

History | View | Annotate | Download (6.3 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
from ganeti import ssconf
34

    
35

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

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

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

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

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

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

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

    
70

    
71
class SshRunner:
72
  """Wrapper for SSH commands.
73

74
  """
75
  def __init__(self, sstore=None):
76
    if sstore is None:
77
      self.sstore = ssconf.SimpleStore()
78
    else:
79
      self.sstore = sstore
80

    
81
  def _BuildSshOptions(self, batch, ask_key, use_cluster_key):
82
    options = [
83
      "-oEscapeChar=none",
84
      "-oHashKnownHosts=no",
85
      "-oGlobalKnownHostsFile=%s" % constants.SSH_KNOWN_HOSTS_FILE,
86
      "-oUserKnownHostsFile=/dev/null",
87
      ]
88

    
89
    if use_cluster_key:
90
      options.append("-oHostKeyAlias=%s" % self.sstore.GetClusterName())
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.extend([
98
        "-oBatchMode=yes",
99
        "-oStrictHostKeyChecking=yes",
100
        ])
101

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

    
107
    return options
108

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

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

122
    Returns:
123
      The ssh call to run 'command' on the remote host.
124

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

    
133
  def Run(self, *args, **kwargs):
134
    """Runs a command on a remote node.
135

136
    This method has the same return value as `utils.RunCmd()`, which it
137
    uses to launch ssh.
138

139
    Args:
140
      See SshRunner.BuildCmd.
141

142
    Returns:
143
      `utils.RunResult` like `utils.RunCmd()`
144

145
    """
146
    return utils.RunCmd(self.BuildCmd(*args, **kwargs))
147

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

151
    Args:
152
      node: node in the cluster
153
      filename: absolute pathname of a local file
154

155
    Returns:
156
      success: True/False
157

158
    """
159
    if not os.path.isabs(filename):
160
      logger.Error("file %s must be an absolute path" % (filename))
161
      return False
162

    
163
    if not os.path.isfile(filename):
164
      logger.Error("file %s does not exist" % (filename))
165
      return False
166

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

    
172
    result = utils.RunCmd(command)
173

    
174
    if result.failed:
175
      logger.Error("copy to node %s failed (%s) error %s,"
176
                   " command was %s" %
177
                   (node, result.fail_reason, result.output, result.cmd))
178

    
179
    return not result.failed
180

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

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

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

192
    Args:
193
      node: nodename of a host to check. can be short or full qualified hostname
194

195
    Returns:
196
      (success, detail)
197
      where
198
        success: True/False
199
        detail: String with details
200

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

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

    
211
    remotehostname = retval.stdout.strip()
212

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

    
216
    return True, "host matches"
217

    
218

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

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