Statistics
| Branch: | Tag: | Revision:

root / lib / ssh.py @ 51144e33

History | View | Annotate | Download (6.9 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
KNOWN_HOSTS_OPTS = [
37
  "-oGlobalKnownHostsFile=%s" % constants.SSH_KNOWN_HOSTS_FILE,
38
  "-oUserKnownHostsFile=/dev/null",
39
  ]
40

    
41
# Note: BATCH_MODE conflicts with ASK_KEY
42
BATCH_MODE_OPTS = [
43
  "-oBatchMode=yes",
44
  "-oEscapeChar=none",
45
  "-oStrictHostKeyChecking=yes",
46
  ]
47

    
48
ASK_KEY_OPTS = [
49
  "-oEscapeChar=none",
50
  "-oHashKnownHosts=no",
51
  "-oStrictHostKeyChecking=ask",
52
  ]
53

    
54

    
55
def GetUserFiles(user, mkdir=False):
56
  """Return the paths of a user's ssh files.
57

58
  The function will return a triplet (priv_key_path, pub_key_path,
59
  auth_key_path) that are used for ssh authentication. Currently, the
60
  keys used are DSA keys, so this function will return:
61
  (~user/.ssh/id_dsa, ~user/.ssh/id_dsa.pub,
62
  ~user/.ssh/authorized_keys).
63

64
  If the optional parameter mkdir is True, the ssh directory will be
65
  created if it doesn't exist.
66

67
  Regardless of the mkdir parameters, the script will raise an error
68
  if ~user/.ssh is not a directory.
69

70
  """
71
  user_dir = utils.GetHomeDir(user)
72
  if not user_dir:
73
    raise errors.OpExecError("Cannot resolve home of user %s" % user)
74

    
75
  ssh_dir = os.path.join(user_dir, ".ssh")
76
  if not os.path.lexists(ssh_dir):
77
    if mkdir:
78
      try:
79
        os.mkdir(ssh_dir, 0700)
80
      except EnvironmentError, err:
81
        raise errors.OpExecError("Can't create .ssh dir for user %s: %s" %
82
                                 (user, str(err)))
83
  elif not os.path.isdir(ssh_dir):
84
    raise errors.OpExecError("path ~%s/.ssh is not a directory" % user)
85

    
86
  return [os.path.join(ssh_dir, base)
87
          for base in ["id_dsa", "id_dsa.pub", "authorized_keys"]]
88

    
89

    
90
class SshRunner:
91
  """Wrapper for SSH commands.
92

93
  """
94
  def __init__(self, sstore=None):
95
    if sstore is None:
96
      self.sstore = ssconf.SimpleStore()
97
    else:
98
      self.sstore = sstore
99

    
100
  def _GetHostKeyAliasOption(self):
101
    return "-oHostKeyAlias=%s" % self.sstore.GetClusterName()
102

    
103
  def BuildCmd(self, hostname, user, command, batch=True, ask_key=False,
104
               tty=False, use_cluster_key=True):
105
    """Build an ssh command to execute a command on a remote node.
106

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

116
    Returns:
117
      The ssh call to run 'command' on the remote host.
118

119
    """
120
    argv = [constants.SSH, "-q"]
121
    argv.extend(KNOWN_HOSTS_OPTS)
122
    if use_cluster_key:
123
      argv.append(self._GetHostKeyAliasOption())
124
    if batch:
125
      # if we are in batch mode, we can't ask the key
126
      if ask_key:
127
        raise errors.ProgrammerError("SSH call requested conflicting options")
128
      argv.extend(BATCH_MODE_OPTS)
129
    elif ask_key:
130
      argv.extend(ASK_KEY_OPTS)
131
    if tty:
132
      argv.append("-t")
133
    argv.extend(["%s@%s" % (user, hostname), command])
134
    return argv
135

    
136
  def Run(self, hostname, user, command, batch=True, ask_key=False,
137
          use_cluster_key=True):
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
      hostname: the target host, string
145
      user: user to auth as
146
      command: the command
147
      batch: if true, ssh will run in batch mode with no prompting
148
      ask_key: if true, ssh will run with StrictHostKeyChecking=ask, so that
149
               we can connect to an unknown host (not valid in batch mode)
150

151
    Returns:
152
      `utils.RunResult` like `utils.RunCmd()`
153

154
    """
155
    return utils.RunCmd(self.BuildCmd(hostname, user, command, batch=batch,
156
                                      ask_key=ask_key,
157
                                      use_cluster_key=use_cluster_key))
158

    
159
  def CopyFileToNode(self, node, filename):
160
    """Copy a file to another node with scp.
161

162
    Args:
163
      node: node in the cluster
164
      filename: absolute pathname of a local file
165

166
    Returns:
167
      success: True/False
168

169
    """
170
    if not os.path.isabs(filename):
171
      logger.Error("file %s must be an absolute path" % (filename))
172
      return False
173

    
174
    if not os.path.isfile(filename):
175
      logger.Error("file %s does not exist" % (filename))
176
      return False
177

    
178
    command = [constants.SCP, "-q", "-p"]
179
    command.extend(KNOWN_HOSTS_OPTS)
180
    command.extend(BATCH_MODE_OPTS)
181
    command.append(self._GetHostKeyAliasOption())
182
    command.append(filename)
183
    command.append("%s:%s" % (node, filename))
184

    
185
    result = utils.RunCmd(command)
186

    
187
    if result.failed:
188
      logger.Error("copy to node %s failed (%s) error %s,"
189
                   " command was %s" %
190
                   (node, result.fail_reason, result.output, result.cmd))
191

    
192
    return not result.failed
193

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

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

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

205
    Args:
206
      node: nodename of a host to check. can be short or full qualified hostname
207

208
    Returns:
209
      (success, detail)
210
      where
211
        success: True/False
212
        detail: String with details
213

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

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

    
224
    remotehostname = retval.stdout.strip()
225

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

    
229
    return True, "host matches"
230

    
231

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

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