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
33 def SSHCall(hostname, user, command, batch=True, ask_key=False):
34 """Execute a command on a remote node.
36 This method has the same return value as `utils.RunCmd()`, which it
40 hostname: the target host, string
45 `utils.RunResult` as for `utils.RunCmd()`
48 argv = ["ssh", "-q", "-oEscapeChar=none"]
50 argv.append("-oBatchMode=yes")
51 # if we are in batch mode, we can't ask the key
53 raise errors.ProgrammerError("SSH call requested conflicting options")
55 argv.append("-oStrictHostKeyChecking=ask")
56 argv.append("-oHashKnownHosts=no")
58 argv.append("-oStrictHostKeyChecking=yes")
59 argv.extend(["%s@%s" % (user, hostname), command])
60 return utils.RunCmd(argv)
63 def CopyFileToNode(node, filename):
64 """Copy a file to another node with scp.
67 node: node in the cluster
68 filename: absolute pathname of a local file
74 if not os.path.isfile(filename):
75 logger.Error("file %s does not exist" % (filename))
78 if not os.path.isabs(filename):
79 logger.Error("file %s must be an absolute path" % (filename))
82 command = ["scp", "-q", "-p", "-oStrictHostKeyChecking=yes",
83 "-oBatchMode=yes", filename, "%s:%s" % (node, filename)]
85 result = utils.RunCmd(command)
88 logger.Error("copy to node %s failed (%s) error %s,"
90 (node, result.fail_reason, result.output, result.cmd))
92 return not result.failed
95 def VerifyNodeHostname(node):
96 """Verify hostname consistency via SSH.
99 This functions connects via ssh to a node and compares the hostname
100 reported by the node to the name with have (the one that we
103 This is used to detect problems in ssh known_hosts files
104 (conflicting known hosts) and incosistencies between dns/hosts
105 entries and local machine names
108 node: nodename of a host to check. can be short or full qualified hostname
114 detail: String with details
117 retval = SSHCall(node, 'root', 'hostname')
121 output = retval.output
123 msg += ": %s" % output
126 remotehostname = retval.stdout.strip()
128 if not remotehostname or remotehostname != node:
129 return False, "hostname mismatch, got %s" % remotehostname
131 return True, "host matches"