4 # Copyright (C) 2006, 2007 Google Inc.
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.
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.
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
22 """Module encapsulating ssh functionality.
29 from ganeti import logger
30 from ganeti import utils
31 from ganeti import errors
32 from ganeti import constants
35 def GetUserFiles(user, mkdir=False):
36 """Return the paths of a user's ssh files.
38 The function will return a triplet (priv_key_path, pub_key_path,
39 auth_key_path) that are used for ssh authentication. Currently, the
40 keys used are DSA keys, so this function will return:
41 (~user/.ssh/id_dsa, ~user/.ssh/id_dsa.pub,
42 ~user/.ssh/authorized_keys).
44 If the optional parameter mkdir is True, the ssh directory will be
45 created if it doesn't exist.
47 Regardless of the mkdir parameters, the script will raise an error
48 if ~user/.ssh is not a directory.
51 user_dir = utils.GetHomeDir(user)
53 raise errors.OpExecError("Cannot resolve home of user %s" % user)
55 ssh_dir = os.path.join(user_dir, ".ssh")
56 if not os.path.lexists(ssh_dir):
59 os.mkdir(ssh_dir, 0700)
60 except EnvironmentError, err:
61 raise errors.OpExecError("Can't create .ssh dir for user %s: %s" %
63 elif not os.path.isdir(ssh_dir):
64 raise errors.OpExecError("path ~%s/.ssh is not a directory" % user)
66 return [os.path.join(ssh_dir, base)
67 for base in ["id_dsa", "id_dsa.pub", "authorized_keys"]]
71 """Wrapper for SSH commands.
74 def __init__(self, cluster_name):
75 self.cluster_name = cluster_name
77 def _BuildSshOptions(self, batch, ask_key, use_cluster_key,
81 "-oHashKnownHosts=no",
82 "-oGlobalKnownHostsFile=%s" % constants.SSH_KNOWN_HOSTS_FILE,
83 "-oUserKnownHostsFile=/dev/null",
87 options.append("-oHostKeyAlias=%s" % self.cluster_name)
89 # TODO: Too many boolean options, maybe convert them to more descriptive
92 # Note: ask_key conflicts with batch mode
95 raise errors.ProgrammerError("SSH call requested conflicting options")
97 options.append("-oBatchMode=yes")
100 options.append("-oStrictHostKeyChecking=yes")
102 options.append("-oStrictHostKeyChecking=no")
106 "-oStrictHostKeyChecking=ask",
111 def BuildCmd(self, hostname, user, command, batch=True, ask_key=False,
112 tty=False, use_cluster_key=True, strict_host_check=True):
113 """Build an ssh command to execute a command on a remote node.
116 hostname: the target host, string
117 user: user to auth as
119 batch: if true, ssh will run in batch mode with no prompting
120 ask_key: if true, ssh will run with StrictHostKeyChecking=ask, so that
121 we can connect to an unknown host (not valid in batch mode)
122 use_cluster_key: Whether to expect and use the cluster-global SSH key
123 strict_host_check: Whether to check the host's SSH key at all
126 The ssh call to run 'command' on the remote host.
129 argv = [constants.SSH, "-q"]
130 argv.extend(self._BuildSshOptions(batch, ask_key, use_cluster_key,
134 argv.extend(["%s@%s" % (user, hostname), command])
137 def Run(self, *args, **kwargs):
138 """Runs a command on a remote node.
140 This method has the same return value as `utils.RunCmd()`, which it
144 See SshRunner.BuildCmd.
147 `utils.RunResult` like `utils.RunCmd()`
150 return utils.RunCmd(self.BuildCmd(*args, **kwargs))
152 def CopyFileToNode(self, node, filename):
153 """Copy a file to another node with scp.
156 node: node in the cluster
157 filename: absolute pathname of a local file
163 if not os.path.isabs(filename):
164 logger.Error("file %s must be an absolute path" % (filename))
167 if not os.path.isfile(filename):
168 logger.Error("file %s does not exist" % (filename))
171 command = [constants.SCP, "-q", "-p"]
172 command.extend(self._BuildSshOptions(True, False, True, True))
173 command.append(filename)
174 command.append("%s:%s" % (node, filename))
176 result = utils.RunCmd(command)
179 logger.Error("copy to node %s failed (%s) error %s,"
181 (node, result.fail_reason, result.output, result.cmd))
183 return not result.failed
185 def VerifyNodeHostname(self, node):
186 """Verify hostname consistency via SSH.
188 This functions connects via ssh to a node and compares the hostname
189 reported by the node to the name with have (the one that we
192 This is used to detect problems in ssh known_hosts files
193 (conflicting known hosts) and incosistencies between dns/hosts
194 entries and local machine names
197 node: nodename of a host to check. can be short or full qualified hostname
203 detail: String with details
206 retval = self.Run(node, 'root', 'hostname')
210 output = retval.output
212 msg += ": %s" % output
215 remotehostname = retval.stdout.strip()
217 if not remotehostname or remotehostname != node:
218 return False, "hostname mismatch, got %s" % remotehostname
220 return True, "host matches"
223 def WriteKnownHostsFile(cfg, file_name):
224 """Writes the cluster-wide equally known_hosts file.
227 utils.WriteFile(file_name, mode=0700,
228 data="%s ssh-rsa %s\n" % (cfg.GetClusterName(),