Statistics
| Branch: | Tag: | Revision:

root / lib / ssh.py @ eb58f9b1

History | View | Annotate | Download (6.9 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 a8083063 Iustin Pop
29 a8083063 Iustin Pop
from ganeti import logger
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 1ff08570 Michael Hanselmann
from ganeti import ssconf
34 82122173 Iustin Pop
35 82122173 Iustin Pop
36 82122173 Iustin Pop
KNOWN_HOSTS_OPTS = [
37 82122173 Iustin Pop
  "-oGlobalKnownHostsFile=%s" % constants.SSH_KNOWN_HOSTS_FILE,
38 82122173 Iustin Pop
  "-oUserKnownHostsFile=/dev/null",
39 82122173 Iustin Pop
  ]
40 82122173 Iustin Pop
41 82122173 Iustin Pop
# Note: BATCH_MODE conflicts with ASK_KEY
42 82122173 Iustin Pop
BATCH_MODE_OPTS = [
43 82122173 Iustin Pop
  "-oBatchMode=yes",
44 bf3d57b8 Michael Hanselmann
  "-oEscapeChar=none",
45 82122173 Iustin Pop
  "-oStrictHostKeyChecking=yes",
46 82122173 Iustin Pop
  ]
47 82122173 Iustin Pop
48 82122173 Iustin Pop
ASK_KEY_OPTS = [
49 82122173 Iustin Pop
  "-oEscapeChar=none",
50 82122173 Iustin Pop
  "-oHashKnownHosts=no",
51 bf3d57b8 Michael Hanselmann
  "-oStrictHostKeyChecking=ask",
52 82122173 Iustin Pop
  ]
53 82122173 Iustin Pop
54 72f0f7fd Iustin Pop
55 70d9e3d8 Iustin Pop
def GetUserFiles(user, mkdir=False):
56 70d9e3d8 Iustin Pop
  """Return the paths of a user's ssh files.
57 70d9e3d8 Iustin Pop

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

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

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

70 70d9e3d8 Iustin Pop
  """
71 70d9e3d8 Iustin Pop
  user_dir = utils.GetHomeDir(user)
72 70d9e3d8 Iustin Pop
  if not user_dir:
73 70d9e3d8 Iustin Pop
    raise errors.OpExecError("Cannot resolve home of user %s" % user)
74 70d9e3d8 Iustin Pop
75 70d9e3d8 Iustin Pop
  ssh_dir = os.path.join(user_dir, ".ssh")
76 70d9e3d8 Iustin Pop
  if not os.path.lexists(ssh_dir):
77 70d9e3d8 Iustin Pop
    if mkdir:
78 70d9e3d8 Iustin Pop
      try:
79 70d9e3d8 Iustin Pop
        os.mkdir(ssh_dir, 0700)
80 70d9e3d8 Iustin Pop
      except EnvironmentError, err:
81 70d9e3d8 Iustin Pop
        raise errors.OpExecError("Can't create .ssh dir for user %s: %s" %
82 70d9e3d8 Iustin Pop
                                 (user, str(err)))
83 70d9e3d8 Iustin Pop
  elif not os.path.isdir(ssh_dir):
84 70d9e3d8 Iustin Pop
    raise errors.OpExecError("path ~%s/.ssh is not a directory" % user)
85 70d9e3d8 Iustin Pop
86 70d9e3d8 Iustin Pop
  return [os.path.join(ssh_dir, base)
87 70d9e3d8 Iustin Pop
          for base in ["id_dsa", "id_dsa.pub", "authorized_keys"]]
88 70d9e3d8 Iustin Pop
89 70d9e3d8 Iustin Pop
90 c92b310a Michael Hanselmann
class SshRunner:
91 c92b310a Michael Hanselmann
  """Wrapper for SSH commands.
92 a8083063 Iustin Pop

93 a8083063 Iustin Pop
  """
94 1ff08570 Michael Hanselmann
  def __init__(self, sstore=None):
95 1ff08570 Michael Hanselmann
    if sstore is None:
96 1ff08570 Michael Hanselmann
      self.sstore = ssconf.SimpleStore()
97 1ff08570 Michael Hanselmann
    else:
98 1ff08570 Michael Hanselmann
      self.sstore = sstore
99 1ff08570 Michael Hanselmann
100 1ff08570 Michael Hanselmann
  def _GetHostKeyAliasOption(self):
101 1ff08570 Michael Hanselmann
    return "-oHostKeyAlias=%s" % self.sstore.GetClusterName()
102 1ff08570 Michael Hanselmann
103 8f07f831 Michael Hanselmann
  def BuildCmd(self, hostname, user, command, batch=True, ask_key=False,
104 51144e33 Michael Hanselmann
               tty=False, use_cluster_key=True):
105 c92b310a Michael Hanselmann
    """Build an ssh command to execute a command on a remote node.
106 c92b310a Michael Hanselmann

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

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

119 c92b310a Michael Hanselmann
    """
120 fff33d70 Michael Hanselmann
    argv = [constants.SSH, "-q"]
121 c92b310a Michael Hanselmann
    argv.extend(KNOWN_HOSTS_OPTS)
122 51144e33 Michael Hanselmann
    if use_cluster_key:
123 51144e33 Michael Hanselmann
      argv.append(self._GetHostKeyAliasOption())
124 c92b310a Michael Hanselmann
    if batch:
125 c92b310a Michael Hanselmann
      # if we are in batch mode, we can't ask the key
126 c92b310a Michael Hanselmann
      if ask_key:
127 c92b310a Michael Hanselmann
        raise errors.ProgrammerError("SSH call requested conflicting options")
128 c92b310a Michael Hanselmann
      argv.extend(BATCH_MODE_OPTS)
129 c92b310a Michael Hanselmann
    elif ask_key:
130 c92b310a Michael Hanselmann
      argv.extend(ASK_KEY_OPTS)
131 8f07f831 Michael Hanselmann
    if tty:
132 8f07f831 Michael Hanselmann
      argv.append("-t")
133 c92b310a Michael Hanselmann
    argv.extend(["%s@%s" % (user, hostname), command])
134 c92b310a Michael Hanselmann
    return argv
135 c92b310a Michael Hanselmann
136 51144e33 Michael Hanselmann
  def Run(self, hostname, user, command, batch=True, ask_key=False,
137 51144e33 Michael Hanselmann
          use_cluster_key=True):
138 c92b310a Michael Hanselmann
    """Runs a command on a remote node.
139 c92b310a Michael Hanselmann

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

143 c92b310a Michael Hanselmann
    Args:
144 c92b310a Michael Hanselmann
      hostname: the target host, string
145 c92b310a Michael Hanselmann
      user: user to auth as
146 c92b310a Michael Hanselmann
      command: the command
147 c92b310a Michael Hanselmann
      batch: if true, ssh will run in batch mode with no prompting
148 c92b310a Michael Hanselmann
      ask_key: if true, ssh will run with StrictHostKeyChecking=ask, so that
149 c92b310a Michael Hanselmann
               we can connect to an unknown host (not valid in batch mode)
150 c92b310a Michael Hanselmann

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

154 c92b310a Michael Hanselmann
    """
155 c92b310a Michael Hanselmann
    return utils.RunCmd(self.BuildCmd(hostname, user, command, batch=batch,
156 51144e33 Michael Hanselmann
                                      ask_key=ask_key,
157 51144e33 Michael Hanselmann
                                      use_cluster_key=use_cluster_key))
158 c92b310a Michael Hanselmann
159 c92b310a Michael Hanselmann
  def CopyFileToNode(self, node, filename):
160 c92b310a Michael Hanselmann
    """Copy a file to another node with scp.
161 c92b310a Michael Hanselmann

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

166 c92b310a Michael Hanselmann
    Returns:
167 c92b310a Michael Hanselmann
      success: True/False
168 a8083063 Iustin Pop

169 c92b310a Michael Hanselmann
    """
170 c92b310a Michael Hanselmann
    if not os.path.isabs(filename):
171 c92b310a Michael Hanselmann
      logger.Error("file %s must be an absolute path" % (filename))
172 c92b310a Michael Hanselmann
      return False
173 a8083063 Iustin Pop
174 1d544ba3 Michael Hanselmann
    if not os.path.isfile(filename):
175 1d544ba3 Michael Hanselmann
      logger.Error("file %s does not exist" % (filename))
176 1d544ba3 Michael Hanselmann
      return False
177 1d544ba3 Michael Hanselmann
178 fff33d70 Michael Hanselmann
    command = [constants.SCP, "-q", "-p"]
179 c92b310a Michael Hanselmann
    command.extend(KNOWN_HOSTS_OPTS)
180 c92b310a Michael Hanselmann
    command.extend(BATCH_MODE_OPTS)
181 1ff08570 Michael Hanselmann
    command.append(self._GetHostKeyAliasOption())
182 c92b310a Michael Hanselmann
    command.append(filename)
183 c92b310a Michael Hanselmann
    command.append("%s:%s" % (node, filename))
184 a8083063 Iustin Pop
185 c92b310a Michael Hanselmann
    result = utils.RunCmd(command)
186 a8083063 Iustin Pop
187 c92b310a Michael Hanselmann
    if result.failed:
188 c92b310a Michael Hanselmann
      logger.Error("copy to node %s failed (%s) error %s,"
189 c92b310a Michael Hanselmann
                   " command was %s" %
190 c92b310a Michael Hanselmann
                   (node, result.fail_reason, result.output, result.cmd))
191 a8083063 Iustin Pop
192 c92b310a Michael Hanselmann
    return not result.failed
193 a8083063 Iustin Pop
194 c92b310a Michael Hanselmann
  def VerifyNodeHostname(self, node):
195 c92b310a Michael Hanselmann
    """Verify hostname consistency via SSH.
196 a8083063 Iustin Pop

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

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

205 c92b310a Michael Hanselmann
    Args:
206 c92b310a Michael Hanselmann
      node: nodename of a host to check. can be short or full qualified hostname
207 a8083063 Iustin Pop

208 c92b310a Michael Hanselmann
    Returns:
209 c92b310a Michael Hanselmann
      (success, detail)
210 c92b310a Michael Hanselmann
      where
211 c92b310a Michael Hanselmann
        success: True/False
212 c92b310a Michael Hanselmann
        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 75a5f456 Michael Hanselmann
def WriteKnownHostsFile(cfg, sstore, 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 75a5f456 Michael Hanselmann
                  data="%s ssh-rsa %s\n" % (sstore.GetClusterName(),
238 75a5f456 Michael Hanselmann
                                            cfg.GetHostKey()))