Statistics
| Branch: | Tag: | Revision:

root / lib / ssh.py @ 6e06b36c

History | View | Annotate | Download (5.9 kB)

1
#
2
#
3

    
4
# Copyright (C) 2006, 2007 Google Inc.
5
#
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.
10
#
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.
15
#
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
19
# 02110-1301, USA.
20

    
21

    
22
"""Module encapsulating ssh functionality.
23

24
"""
25

    
26

    
27
import os
28

    
29
from ganeti import logger
30
from ganeti import utils
31
from ganeti import errors
32
from ganeti import constants
33

    
34

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

    
38

    
39
KNOWN_HOSTS_OPTS = [
40
  "-oGlobalKnownHostsFile=%s" % constants.SSH_KNOWN_HOSTS_FILE,
41
  "-oUserKnownHostsFile=/dev/null",
42
  ]
43

    
44
# Note: BATCH_MODE conflicts with ASK_KEY
45
BATCH_MODE_OPTS = [
46
  "-oEscapeChar=none",
47
  "-oBatchMode=yes",
48
  "-oStrictHostKeyChecking=yes",
49
  ]
50

    
51
ASK_KEY_OPTS = [
52
  "-oStrictHostKeyChecking=ask",
53
  "-oEscapeChar=none",
54
  "-oHashKnownHosts=no",
55
  ]
56

    
57

    
58
def GetUserFiles(user, mkdir=False):
59
  """Return the paths of a user's ssh files.
60

61
  The function will return a triplet (priv_key_path, pub_key_path,
62
  auth_key_path) that are used for ssh authentication. Currently, the
63
  keys used are DSA keys, so this function will return:
64
  (~user/.ssh/id_dsa, ~user/.ssh/id_dsa.pub,
65
  ~user/.ssh/authorized_keys).
66

67
  If the optional parameter mkdir is True, the ssh directory will be
68
  created if it doesn't exist.
69

70
  Regardless of the mkdir parameters, the script will raise an error
71
  if ~user/.ssh is not a directory.
72

73
  """
74
  user_dir = utils.GetHomeDir(user)
75
  if not user_dir:
76
    raise errors.OpExecError("Cannot resolve home of user %s" % user)
77

    
78
  ssh_dir = os.path.join(user_dir, ".ssh")
79
  if not os.path.lexists(ssh_dir):
80
    if mkdir:
81
      try:
82
        os.mkdir(ssh_dir, 0700)
83
      except EnvironmentError, err:
84
        raise errors.OpExecError("Can't create .ssh dir for user %s: %s" %
85
                                 (user, str(err)))
86
  elif not os.path.isdir(ssh_dir):
87
    raise errors.OpExecError("path ~%s/.ssh is not a directory" % user)
88

    
89
  return [os.path.join(ssh_dir, base)
90
          for base in ["id_dsa", "id_dsa.pub", "authorized_keys"]]
91

    
92

    
93
def BuildSSHCmd(hostname, user, command, batch=True, ask_key=False):
94
  """Build an ssh string to execute a command on a remote node.
95

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

104
  Returns:
105
    The ssh call to run 'command' on the remote host.
106

107
  """
108
  argv = ["ssh", "-q"]
109
  argv.extend(KNOWN_HOSTS_OPTS)
110
  if batch:
111
    # if we are in batch mode, we can't ask the key
112
    if ask_key:
113
      raise errors.ProgrammerError("SSH call requested conflicting options")
114
    argv.extend(BATCH_MODE_OPTS)
115
  elif ask_key:
116
    argv.extend(ASK_KEY_OPTS)
117
  argv.extend(["%s@%s" % (user, hostname), command])
118
  return argv
119

    
120

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

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

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

135
  Returns:
136
    `utils.RunResult` as for `utils.RunCmd()`
137

138
  """
139
  return utils.RunCmd(BuildSSHCmd(hostname, user, command,
140
                                  batch=batch, ask_key=ask_key))
141

    
142

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

146
  Args:
147
    node: node in the cluster
148
    filename: absolute pathname of a local file
149

150
  Returns:
151
    success: True/False
152

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

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

    
162
  command = ["scp", "-q", "-p"]
163
  command.extend(KNOWN_HOSTS_OPTS)
164
  command.extend(BATCH_MODE_OPTS)
165
  command.append(filename)
166
  command.append("%s:%s" % (node, filename))
167

    
168
  result = utils.RunCmd(command)
169

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

    
175
  return not result.failed
176

    
177

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

181

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

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

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

193
  Returns:
194
    (success, detail)
195
    where
196
      success: True/False
197
      detail: String with details
198

199
  """
200
  retval = SSHCall(node, 'root', 'hostname')
201

    
202
  if retval.failed:
203
    msg = "ssh problem"
204
    output = retval.output
205
    if output:
206
      msg += ": %s" % output
207
    return False, msg
208

    
209
  remotehostname = retval.stdout.strip()
210

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

    
214
  return True, "host matches"