Statistics
| Branch: | Tag: | Revision:

root / lib / ssh.py @ 70d9e3d8

History | View | Annotate | Download (5.8 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, batch=batch, ask_key=ask_key))
140

    
141

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

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

149
  Returns:
150
    success: True/False
151

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

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

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

    
167
  result = utils.RunCmd(command)
168

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

    
174
  return not result.failed
175

    
176

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

180

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

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

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

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

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

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

    
208
  remotehostname = retval.stdout.strip()
209

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

    
213
  return True, "host matches"