Statistics
| Branch: | Tag: | Revision:

root / lib / ssh.py @ 38e250ba

History | View | Annotate | Download (7.1 kB)

1 2f31098c Iustin Pop
#
2 a8083063 Iustin Pop
#
3 a8083063 Iustin Pop
4 a8083063 Iustin Pop
# Copyright (C) 2006, 2007 Google Inc.
5 a8083063 Iustin Pop
#
6 a8083063 Iustin Pop
# This program is free software; you can redistribute it and/or modify
7 a8083063 Iustin Pop
# it under the terms of the GNU General Public License as published by
8 a8083063 Iustin Pop
# the Free Software Foundation; either version 2 of the License, or
9 a8083063 Iustin Pop
# (at your option) any later version.
10 a8083063 Iustin Pop
#
11 a8083063 Iustin Pop
# This program is distributed in the hope that it will be useful, but
12 a8083063 Iustin Pop
# WITHOUT ANY WARRANTY; without even the implied warranty of
13 a8083063 Iustin Pop
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14 a8083063 Iustin Pop
# General Public License for more details.
15 a8083063 Iustin Pop
#
16 a8083063 Iustin Pop
# You should have received a copy of the GNU General Public License
17 a8083063 Iustin Pop
# along with this program; if not, write to the Free Software
18 a8083063 Iustin Pop
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
19 a8083063 Iustin Pop
# 02110-1301, USA.
20 a8083063 Iustin Pop
21 a8083063 Iustin Pop
22 a8083063 Iustin Pop
"""Module encapsulating ssh functionality.
23 a8083063 Iustin Pop

24 a8083063 Iustin Pop
"""
25 a8083063 Iustin Pop
26 a8083063 Iustin Pop
27 a8083063 Iustin Pop
import os
28 9c034cbe Iustin Pop
import logging
29 a8083063 Iustin Pop
30 a8083063 Iustin Pop
from ganeti import utils
31 a8083063 Iustin Pop
from ganeti import errors
32 82122173 Iustin Pop
from ganeti import constants
33 82122173 Iustin Pop
34 82122173 Iustin Pop
35 70d9e3d8 Iustin Pop
def GetUserFiles(user, mkdir=False):
36 70d9e3d8 Iustin Pop
  """Return the paths of a user's ssh files.
37 70d9e3d8 Iustin Pop

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

44 70d9e3d8 Iustin Pop
  If the optional parameter mkdir is True, the ssh directory will be
45 70d9e3d8 Iustin Pop
  created if it doesn't exist.
46 70d9e3d8 Iustin Pop

47 70d9e3d8 Iustin Pop
  Regardless of the mkdir parameters, the script will raise an error
48 70d9e3d8 Iustin Pop
  if ~user/.ssh is not a directory.
49 70d9e3d8 Iustin Pop

50 70d9e3d8 Iustin Pop
  """
51 70d9e3d8 Iustin Pop
  user_dir = utils.GetHomeDir(user)
52 70d9e3d8 Iustin Pop
  if not user_dir:
53 70d9e3d8 Iustin Pop
    raise errors.OpExecError("Cannot resolve home of user %s" % user)
54 70d9e3d8 Iustin Pop
55 70d9e3d8 Iustin Pop
  ssh_dir = os.path.join(user_dir, ".ssh")
56 70d9e3d8 Iustin Pop
  if not os.path.lexists(ssh_dir):
57 70d9e3d8 Iustin Pop
    if mkdir:
58 70d9e3d8 Iustin Pop
      try:
59 70d9e3d8 Iustin Pop
        os.mkdir(ssh_dir, 0700)
60 70d9e3d8 Iustin Pop
      except EnvironmentError, err:
61 70d9e3d8 Iustin Pop
        raise errors.OpExecError("Can't create .ssh dir for user %s: %s" %
62 70d9e3d8 Iustin Pop
                                 (user, str(err)))
63 70d9e3d8 Iustin Pop
  elif not os.path.isdir(ssh_dir):
64 70d9e3d8 Iustin Pop
    raise errors.OpExecError("path ~%s/.ssh is not a directory" % user)
65 70d9e3d8 Iustin Pop
66 70d9e3d8 Iustin Pop
  return [os.path.join(ssh_dir, base)
67 70d9e3d8 Iustin Pop
          for base in ["id_dsa", "id_dsa.pub", "authorized_keys"]]
68 70d9e3d8 Iustin Pop
69 70d9e3d8 Iustin Pop
70 c92b310a Michael Hanselmann
class SshRunner:
71 c92b310a Michael Hanselmann
  """Wrapper for SSH commands.
72 a8083063 Iustin Pop

73 a8083063 Iustin Pop
  """
74 56bece1f Iustin Pop
  def __init__(self, cluster_name):
75 56bece1f Iustin Pop
    self.cluster_name = cluster_name
76 1ff08570 Michael Hanselmann
77 652d6694 Michael Hanselmann
  def _BuildSshOptions(self, batch, ask_key, use_cluster_key,
78 652d6694 Michael Hanselmann
                       strict_host_check):
79 bf75f132 Iustin Pop
    """Builds a list with needed SSH options.
80 bf75f132 Iustin Pop

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

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

91 bf75f132 Iustin Pop
    """
92 f6d9f4c3 Michael Hanselmann
    options = [
93 f6d9f4c3 Michael Hanselmann
      "-oEscapeChar=none",
94 f6d9f4c3 Michael Hanselmann
      "-oHashKnownHosts=no",
95 f6d9f4c3 Michael Hanselmann
      "-oGlobalKnownHostsFile=%s" % constants.SSH_KNOWN_HOSTS_FILE,
96 f6d9f4c3 Michael Hanselmann
      "-oUserKnownHostsFile=/dev/null",
97 f6d9f4c3 Michael Hanselmann
      ]
98 f6d9f4c3 Michael Hanselmann
99 f6d9f4c3 Michael Hanselmann
    if use_cluster_key:
100 56bece1f Iustin Pop
      options.append("-oHostKeyAlias=%s" % self.cluster_name)
101 f6d9f4c3 Michael Hanselmann
102 652d6694 Michael Hanselmann
    # TODO: Too many boolean options, maybe convert them to more descriptive
103 652d6694 Michael Hanselmann
    # constants.
104 652d6694 Michael Hanselmann
105 f6d9f4c3 Michael Hanselmann
    # Note: ask_key conflicts with batch mode
106 f6d9f4c3 Michael Hanselmann
    if batch:
107 f6d9f4c3 Michael Hanselmann
      if ask_key:
108 f6d9f4c3 Michael Hanselmann
        raise errors.ProgrammerError("SSH call requested conflicting options")
109 f6d9f4c3 Michael Hanselmann
110 652d6694 Michael Hanselmann
      options.append("-oBatchMode=yes")
111 652d6694 Michael Hanselmann
112 652d6694 Michael Hanselmann
      if strict_host_check:
113 652d6694 Michael Hanselmann
        options.append("-oStrictHostKeyChecking=yes")
114 652d6694 Michael Hanselmann
      else:
115 652d6694 Michael Hanselmann
        options.append("-oStrictHostKeyChecking=no")
116 f6d9f4c3 Michael Hanselmann
117 f6d9f4c3 Michael Hanselmann
    elif ask_key:
118 f6d9f4c3 Michael Hanselmann
      options.extend([
119 f6d9f4c3 Michael Hanselmann
        "-oStrictHostKeyChecking=ask",
120 f6d9f4c3 Michael Hanselmann
        ])
121 f6d9f4c3 Michael Hanselmann
122 f6d9f4c3 Michael Hanselmann
    return options
123 1ff08570 Michael Hanselmann
124 8f07f831 Michael Hanselmann
  def BuildCmd(self, hostname, user, command, batch=True, ask_key=False,
125 652d6694 Michael Hanselmann
               tty=False, use_cluster_key=True, strict_host_check=True):
126 c92b310a Michael Hanselmann
    """Build an ssh command to execute a command on a remote node.
127 c92b310a Michael Hanselmann

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

139 c41eea6e Iustin Pop
    @return: the ssh call to run 'command' on the remote host.
140 c92b310a Michael Hanselmann

141 c92b310a Michael Hanselmann
    """
142 fff33d70 Michael Hanselmann
    argv = [constants.SSH, "-q"]
143 652d6694 Michael Hanselmann
    argv.extend(self._BuildSshOptions(batch, ask_key, use_cluster_key,
144 652d6694 Michael Hanselmann
                                      strict_host_check))
145 8f07f831 Michael Hanselmann
    if tty:
146 8f07f831 Michael Hanselmann
      argv.append("-t")
147 c92b310a Michael Hanselmann
    argv.extend(["%s@%s" % (user, hostname), command])
148 c92b310a Michael Hanselmann
    return argv
149 c92b310a Michael Hanselmann
150 54ab6aec Michael Hanselmann
  def Run(self, *args, **kwargs):
151 c92b310a Michael Hanselmann
    """Runs a command on a remote node.
152 c92b310a Michael Hanselmann

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

156 c41eea6e Iustin Pop
    Args: see SshRunner.BuildCmd.
157 c92b310a Michael Hanselmann

158 c41eea6e Iustin Pop
    @rtype: L{utils.RunResult}
159 c41eea6e Iustin Pop
    @return: the result as from L{utils.RunCmd()}
160 c92b310a Michael Hanselmann

161 c92b310a Michael Hanselmann
    """
162 54ab6aec Michael Hanselmann
    return utils.RunCmd(self.BuildCmd(*args, **kwargs))
163 c92b310a Michael Hanselmann
164 c92b310a Michael Hanselmann
  def CopyFileToNode(self, node, filename):
165 c92b310a Michael Hanselmann
    """Copy a file to another node with scp.
166 c92b310a Michael Hanselmann

167 c41eea6e Iustin Pop
    @param node: node in the cluster
168 c41eea6e Iustin Pop
    @param filename: absolute pathname of a local file
169 c92b310a Michael Hanselmann

170 c41eea6e Iustin Pop
    @rtype: boolean
171 c41eea6e Iustin Pop
    @return: the success of the operation
172 a8083063 Iustin Pop

173 c92b310a Michael Hanselmann
    """
174 c92b310a Michael Hanselmann
    if not os.path.isabs(filename):
175 23828f1c Iustin Pop
      logging.error("File %s must be an absolute path", filename)
176 c92b310a Michael Hanselmann
      return False
177 a8083063 Iustin Pop
178 1d544ba3 Michael Hanselmann
    if not os.path.isfile(filename):
179 23828f1c Iustin Pop
      logging.error("File %s does not exist", filename)
180 1d544ba3 Michael Hanselmann
      return False
181 1d544ba3 Michael Hanselmann
182 fff33d70 Michael Hanselmann
    command = [constants.SCP, "-q", "-p"]
183 652d6694 Michael Hanselmann
    command.extend(self._BuildSshOptions(True, False, True, True))
184 c92b310a Michael Hanselmann
    command.append(filename)
185 c92b310a Michael Hanselmann
    command.append("%s:%s" % (node, filename))
186 a8083063 Iustin Pop
187 c92b310a Michael Hanselmann
    result = utils.RunCmd(command)
188 a8083063 Iustin Pop
189 c92b310a Michael Hanselmann
    if result.failed:
190 23828f1c Iustin Pop
      logging.error("Copy to node %s failed (%s) error %s,"
191 23828f1c Iustin Pop
                    " command was %s",
192 23828f1c Iustin Pop
                    node, result.fail_reason, result.output, result.cmd)
193 a8083063 Iustin Pop
194 c92b310a Michael Hanselmann
    return not result.failed
195 a8083063 Iustin Pop
196 c92b310a Michael Hanselmann
  def VerifyNodeHostname(self, node):
197 c92b310a Michael Hanselmann
    """Verify hostname consistency via SSH.
198 a8083063 Iustin Pop

199 c92b310a Michael Hanselmann
    This functions connects via ssh to a node and compares the hostname
200 c92b310a Michael Hanselmann
    reported by the node to the name with have (the one that we
201 c92b310a Michael Hanselmann
    connected to).
202 a8083063 Iustin Pop

203 c92b310a Michael Hanselmann
    This is used to detect problems in ssh known_hosts files
204 c92b310a Michael Hanselmann
    (conflicting known hosts) and incosistencies between dns/hosts
205 c92b310a Michael Hanselmann
    entries and local machine names
206 a8083063 Iustin Pop

207 c41eea6e Iustin Pop
    @param node: nodename of a host to check; can be short or
208 c41eea6e Iustin Pop
        full qualified hostname
209 a8083063 Iustin Pop

210 c41eea6e Iustin Pop
    @return: (success, detail), where:
211 c41eea6e Iustin Pop
        - success: True/False
212 c41eea6e Iustin Pop
        - detail: string with details
213 a8083063 Iustin Pop

214 c92b310a Michael Hanselmann
    """
215 c92b310a Michael Hanselmann
    retval = self.Run(node, 'root', 'hostname')
216 a8083063 Iustin Pop
217 c92b310a Michael Hanselmann
    if retval.failed:
218 c92b310a Michael Hanselmann
      msg = "ssh problem"
219 c92b310a Michael Hanselmann
      output = retval.output
220 c92b310a Michael Hanselmann
      if output:
221 c92b310a Michael Hanselmann
        msg += ": %s" % output
222 c92b310a Michael Hanselmann
      return False, msg
223 a8083063 Iustin Pop
224 c92b310a Michael Hanselmann
    remotehostname = retval.stdout.strip()
225 a8083063 Iustin Pop
226 c92b310a Michael Hanselmann
    if not remotehostname or remotehostname != node:
227 c92b310a Michael Hanselmann
      return False, "hostname mismatch, got %s" % remotehostname
228 a8083063 Iustin Pop
229 c92b310a Michael Hanselmann
    return True, "host matches"
230 75a5f456 Michael Hanselmann
231 75a5f456 Michael Hanselmann
232 7688d0d3 Michael Hanselmann
def WriteKnownHostsFile(cfg, file_name):
233 75a5f456 Michael Hanselmann
  """Writes the cluster-wide equally known_hosts file.
234 75a5f456 Michael Hanselmann

235 75a5f456 Michael Hanselmann
  """
236 75a5f456 Michael Hanselmann
  utils.WriteFile(file_name, mode=0700,
237 7688d0d3 Michael Hanselmann
                  data="%s ssh-rsa %s\n" % (cfg.GetClusterName(),
238 75a5f456 Michael Hanselmann
                                            cfg.GetHostKey()))