ssh.py 4.69 KB
Newer Older
Iustin Pop's avatar
Iustin Pop committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#!/usr/bin/python
#

# Copyright (C) 2006, 2007 Google Inc.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA.


"""Module encapsulating ssh functionality.

"""


import os

from ganeti import logger
from ganeti import utils
from ganeti import errors
Iustin Pop's avatar
Iustin Pop committed
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
from ganeti import constants


__all__ = ["SSHCall", "CopyFileToNode", "VerifyNodeHostname",
           "KNOWN_HOSTS_OPTS", "BATCH_MODE_OPTS", "ASK_KEY_OPTS"]


KNOWN_HOSTS_OPTS = [
  "-oGlobalKnownHostsFile=%s" % constants.SSH_KNOWN_HOSTS_FILE,
  "-oUserKnownHostsFile=/dev/null",
  ]

# Note: BATCH_MODE conflicts with ASK_KEY
BATCH_MODE_OPTS = [
  "-oEscapeChar=none",
  "-oBatchMode=yes",
  "-oStrictHostKeyChecking=yes",
  ]

ASK_KEY_OPTS = [
  "-oStrictHostKeyChecking=ask",
  "-oEscapeChar=none",
  "-oHashKnownHosts=no",
  ]

57

58
59
def BuildSSHCmd(hostname, user, command, batch=True, ask_key=False):
  """Build an ssh string to execute a command on a remote node.
Iustin Pop's avatar
Iustin Pop committed
60
61
62
63
64

  Args:
    hostname: the target host, string
    user: user to auth as
    command: the command
Iustin Pop's avatar
Iustin Pop committed
65
66
67
    batch: if true, ssh will run in batch mode with no prompting
    ask_key: if true, ssh will run with StrictHostKeyChecking=ask, so that
             we can connect to an unknown host (not valid in batch mode)
Iustin Pop's avatar
Iustin Pop committed
68
69

  Returns:
70
    The ssh call to run 'command' on the remote host.
Iustin Pop's avatar
Iustin Pop committed
71
72

  """
Iustin Pop's avatar
Iustin Pop committed
73
74
  argv = ["ssh", "-q"]
  argv.extend(KNOWN_HOSTS_OPTS)
Iustin Pop's avatar
Iustin Pop committed
75
76
77
  if batch:
    # if we are in batch mode, we can't ask the key
    if ask_key:
78
      raise errors.ProgrammerError("SSH call requested conflicting options")
Iustin Pop's avatar
Iustin Pop committed
79
80
81
    argv.extend(BATCH_MODE_OPTS)
  elif ask_key:
    argv.extend(ASK_KEY_OPTS)
82
  argv.extend(["%s@%s" % (user, hostname), command])
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
  return argv


def SSHCall(hostname, user, command, batch=True, ask_key=False):
  """Execute a command on a remote node.

  This method has the same return value as `utils.RunCmd()`, which it
  uses to launch ssh.

  Args:
    hostname: the target host, string
    user: user to auth as
    command: the command
    batch: if true, ssh will run in batch mode with no prompting
    ask_key: if true, ssh will run with StrictHostKeyChecking=ask, so that
             we can connect to an unknown host (not valid in batch mode)

  Returns:
    `utils.RunResult` as for `utils.RunCmd()`

  """
  return utils.RunCmd(BuildSSHCmd(hostname, user, command, batch=batch, ask_key=ask_key))
Iustin Pop's avatar
Iustin Pop committed
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125


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

  Args:
    node: node in the cluster
    filename: absolute pathname of a local file

  Returns:
    success: True/False

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

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

Iustin Pop's avatar
Iustin Pop committed
126
127
128
129
130
  command = ["scp", "-q", "-p"]
  command.extend(KNOWN_HOSTS_OPTS)
  command.extend(BATCH_MODE_OPTS)
  command.append(filename)
  command.append("%s:%s" % (node, filename))
Iustin Pop's avatar
Iustin Pop committed
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178

  result = utils.RunCmd(command)

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

  return not result.failed


def VerifyNodeHostname(node):
  """Verify hostname consistency via SSH.


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

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

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

  Returns:
    (success, detail)
    where
      success: True/False
      detail: String with details

  """
  retval = SSHCall(node, 'root', 'hostname')

  if retval.failed:
    msg = "ssh problem"
    output = retval.output
    if output:
      msg += ": %s" % output
    return False, msg

  remotehostname = retval.stdout.strip()

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

  return True, "host matches"