PageRenderTime 52ms CodeModel.GetById 12ms RepoModel.GetById 0ms app.codeStats 0ms

/lib/ansible/runner/connection_plugins/paramiko_ssh.py

https://gitlab.com/lileeyao/ansible
Python | 341 lines | 315 code | 4 blank | 22 comment | 1 complexity | 8da1836409263bc266d6172d5a212b4b MD5 | raw file
Possible License(s): GPL-3.0
  1. # (c) 2012, Michael DeHaan <michael.dehaan@gmail.com>
  2. #
  3. # This file is part of Ansible
  4. #
  5. # Ansible is free software: you can redistribute it and/or modify
  6. # it under the terms of the GNU General Public License as published by
  7. # the Free Software Foundation, either version 3 of the License, or
  8. # (at your option) any later version.
  9. #
  10. # Ansible is distributed in the hope that it will be useful,
  11. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. # GNU General Public License for more details.
  14. #
  15. # You should have received a copy of the GNU General Public License
  16. # along with Ansible. If not, see <http://www.gnu.org/licenses/>.
  17. # ---
  18. # The paramiko transport is provided because many distributions, in particular EL6 and before
  19. # do not support ControlPersist in their SSH implementations. This is needed on the Ansible
  20. # control machine to be reasonably efficient with connections. Thus paramiko is faster
  21. # for most users on these platforms. Users with ControlPersist capability can consider
  22. # using -c ssh or configuring the transport in ansible.cfg.
  23. import warnings
  24. import os
  25. import pipes
  26. import socket
  27. import random
  28. import logging
  29. import traceback
  30. import fcntl
  31. import sys
  32. from termios import tcflush, TCIFLUSH
  33. from binascii import hexlify
  34. from ansible.callbacks import vvv
  35. from ansible import errors
  36. from ansible import utils
  37. from ansible import constants as C
  38. AUTHENTICITY_MSG="""
  39. paramiko: The authenticity of host '%s' can't be established.
  40. The %s key fingerprint is %s.
  41. Are you sure you want to continue connecting (yes/no)?
  42. """
  43. # prevent paramiko warning noise -- see http://stackoverflow.com/questions/3920502/
  44. HAVE_PARAMIKO=False
  45. with warnings.catch_warnings():
  46. warnings.simplefilter("ignore")
  47. try:
  48. import paramiko
  49. HAVE_PARAMIKO=True
  50. logging.getLogger("paramiko").setLevel(logging.WARNING)
  51. except ImportError:
  52. pass
  53. class MyAddPolicy(object):
  54. """
  55. Based on AutoAddPolicy in paramiko so we can determine when keys are added
  56. and also prompt for input.
  57. Policy for automatically adding the hostname and new host key to the
  58. local L{HostKeys} object, and saving it. This is used by L{SSHClient}.
  59. """
  60. def __init__(self, runner):
  61. self.runner = runner
  62. def missing_host_key(self, client, hostname, key):
  63. if C.HOST_KEY_CHECKING:
  64. fcntl.lockf(self.runner.process_lockfile, fcntl.LOCK_EX)
  65. fcntl.lockf(self.runner.output_lockfile, fcntl.LOCK_EX)
  66. old_stdin = sys.stdin
  67. sys.stdin = self.runner._new_stdin
  68. fingerprint = hexlify(key.get_fingerprint())
  69. ktype = key.get_name()
  70. # clear out any premature input on sys.stdin
  71. tcflush(sys.stdin, TCIFLUSH)
  72. inp = raw_input(AUTHENTICITY_MSG % (hostname, ktype, fingerprint))
  73. sys.stdin = old_stdin
  74. if inp not in ['yes','y','']:
  75. fcntl.flock(self.runner.output_lockfile, fcntl.LOCK_UN)
  76. fcntl.flock(self.runner.process_lockfile, fcntl.LOCK_UN)
  77. raise errors.AnsibleError("host connection rejected by user")
  78. fcntl.lockf(self.runner.output_lockfile, fcntl.LOCK_UN)
  79. fcntl.lockf(self.runner.process_lockfile, fcntl.LOCK_UN)
  80. key._added_by_ansible_this_time = True
  81. # existing implementation below:
  82. client._host_keys.add(hostname, key.get_name(), key)
  83. # host keys are actually saved in close() function below
  84. # in order to control ordering.
  85. # keep connection objects on a per host basis to avoid repeated attempts to reconnect
  86. SSH_CONNECTION_CACHE = {}
  87. SFTP_CONNECTION_CACHE = {}
  88. class Connection(object):
  89. ''' SSH based connections with Paramiko '''
  90. def __init__(self, runner, host, port, user, password, private_key_file, *args, **kwargs):
  91. self.ssh = None
  92. self.sftp = None
  93. self.runner = runner
  94. self.host = host
  95. self.port = port or 22
  96. self.user = user
  97. self.password = password
  98. self.private_key_file = private_key_file
  99. self.has_pipelining = False
  100. def _cache_key(self):
  101. return "%s__%s__" % (self.host, self.user)
  102. def connect(self):
  103. cache_key = self._cache_key()
  104. if cache_key in SSH_CONNECTION_CACHE:
  105. self.ssh = SSH_CONNECTION_CACHE[cache_key]
  106. else:
  107. self.ssh = SSH_CONNECTION_CACHE[cache_key] = self._connect_uncached()
  108. return self
  109. def _connect_uncached(self):
  110. ''' activates the connection object '''
  111. if not HAVE_PARAMIKO:
  112. raise errors.AnsibleError("paramiko is not installed")
  113. vvv("ESTABLISH CONNECTION FOR USER: %s on PORT %s TO %s" % (self.user, self.port, self.host), host=self.host)
  114. ssh = paramiko.SSHClient()
  115. self.keyfile = os.path.expanduser("~/.ssh/known_hosts")
  116. if C.HOST_KEY_CHECKING:
  117. ssh.load_system_host_keys()
  118. ssh.set_missing_host_key_policy(MyAddPolicy(self.runner))
  119. allow_agent = True
  120. if self.password is not None:
  121. allow_agent = False
  122. try:
  123. if self.private_key_file:
  124. key_filename = os.path.expanduser(self.private_key_file)
  125. elif self.runner.private_key_file:
  126. key_filename = os.path.expanduser(self.runner.private_key_file)
  127. else:
  128. key_filename = None
  129. ssh.connect(self.host, username=self.user, allow_agent=allow_agent, look_for_keys=True,
  130. key_filename=key_filename, password=self.password,
  131. timeout=self.runner.timeout, port=self.port)
  132. except Exception, e:
  133. msg = str(e)
  134. if "PID check failed" in msg:
  135. raise errors.AnsibleError("paramiko version issue, please upgrade paramiko on the machine running ansible")
  136. elif "Private key file is encrypted" in msg:
  137. msg = 'ssh %s@%s:%s : %s\nTo connect as a different user, use -u <username>.' % (
  138. self.user, self.host, self.port, msg)
  139. raise errors.AnsibleConnectionFailed(msg)
  140. else:
  141. raise errors.AnsibleConnectionFailed(msg)
  142. return ssh
  143. def exec_command(self, cmd, tmp_path, sudo_user=None, sudoable=False, executable='/bin/sh', in_data=None, su=None, su_user=None):
  144. ''' run a command on the remote host '''
  145. if in_data:
  146. raise errors.AnsibleError("Internal Error: this module does not support optimized module pipelining")
  147. bufsize = 4096
  148. try:
  149. chan = self.ssh.get_transport().open_session()
  150. except Exception, e:
  151. msg = "Failed to open session"
  152. if len(str(e)) > 0:
  153. msg += ": %s" % str(e)
  154. raise errors.AnsibleConnectionFailed(msg)
  155. if not (self.runner.sudo and sudoable) and not (self.runner.su and su):
  156. if executable:
  157. quoted_command = executable + ' -c ' + pipes.quote(cmd)
  158. else:
  159. quoted_command = cmd
  160. vvv("EXEC %s" % quoted_command, host=self.host)
  161. chan.exec_command(quoted_command)
  162. else:
  163. # sudo usually requires a PTY (cf. requiretty option), therefore
  164. # we give it one by default (pty=True in ansble.cfg), and we try
  165. # to initialise from the calling environment
  166. if C.PARAMIKO_PTY:
  167. chan.get_pty(term=os.getenv('TERM', 'vt100'),
  168. width=int(os.getenv('COLUMNS', 0)),
  169. height=int(os.getenv('LINES', 0)))
  170. if self.runner.sudo or sudoable:
  171. shcmd, prompt, success_key = utils.make_sudo_cmd(sudo_user, executable, cmd)
  172. elif self.runner.su or su:
  173. shcmd, prompt, success_key = utils.make_su_cmd(su_user, executable, cmd)
  174. vvv("EXEC %s" % shcmd, host=self.host)
  175. sudo_output = ''
  176. try:
  177. chan.exec_command(shcmd)
  178. if self.runner.sudo_pass or self.runner.su_pass:
  179. while not sudo_output.endswith(prompt) and success_key not in sudo_output:
  180. chunk = chan.recv(bufsize)
  181. if not chunk:
  182. if 'unknown user' in sudo_output:
  183. raise errors.AnsibleError(
  184. 'user %s does not exist' % sudo_user)
  185. else:
  186. raise errors.AnsibleError('ssh connection ' +
  187. 'closed waiting for password prompt')
  188. sudo_output += chunk
  189. if success_key not in sudo_output:
  190. if sudoable:
  191. chan.sendall(self.runner.sudo_pass + '\n')
  192. elif su:
  193. chan.sendall(self.runner.su_pass + '\n')
  194. except socket.timeout:
  195. raise errors.AnsibleError('ssh timed out waiting for sudo.\n' + sudo_output)
  196. stdout = ''.join(chan.makefile('rb', bufsize))
  197. stderr = ''.join(chan.makefile_stderr('rb', bufsize))
  198. return (chan.recv_exit_status(), '', stdout, stderr)
  199. def put_file(self, in_path, out_path):
  200. ''' transfer a file from local to remote '''
  201. vvv("PUT %s TO %s" % (in_path, out_path), host=self.host)
  202. if not os.path.exists(in_path):
  203. raise errors.AnsibleFileNotFound("file or module does not exist: %s" % in_path)
  204. try:
  205. self.sftp = self.ssh.open_sftp()
  206. except Exception, e:
  207. raise errors.AnsibleError("failed to open a SFTP connection (%s)" % e)
  208. try:
  209. self.sftp.put(in_path, out_path)
  210. except IOError:
  211. raise errors.AnsibleError("failed to transfer file to %s" % out_path)
  212. def _connect_sftp(self):
  213. cache_key = "%s__%s__" % (self.host, self.user)
  214. if cache_key in SFTP_CONNECTION_CACHE:
  215. return SFTP_CONNECTION_CACHE[cache_key]
  216. else:
  217. result = SFTP_CONNECTION_CACHE[cache_key] = self.connect().ssh.open_sftp()
  218. return result
  219. def fetch_file(self, in_path, out_path):
  220. ''' save a remote file to the specified path '''
  221. vvv("FETCH %s TO %s" % (in_path, out_path), host=self.host)
  222. try:
  223. self.sftp = self._connect_sftp()
  224. except Exception, e:
  225. raise errors.AnsibleError("failed to open a SFTP connection (%s)", e)
  226. try:
  227. self.sftp.get(in_path, out_path)
  228. except IOError:
  229. raise errors.AnsibleError("failed to transfer file from %s" % in_path)
  230. def _any_keys_added(self):
  231. added_any = False
  232. for hostname, keys in self.ssh._host_keys.iteritems():
  233. for keytype, key in keys.iteritems():
  234. added_this_time = getattr(key, '_added_by_ansible_this_time', False)
  235. if added_this_time:
  236. return True
  237. return False
  238. def _save_ssh_host_keys(self, filename):
  239. '''
  240. not using the paramiko save_ssh_host_keys function as we want to add new SSH keys at the bottom so folks
  241. don't complain about it :)
  242. '''
  243. if not self._any_keys_added():
  244. return False
  245. path = os.path.expanduser("~/.ssh")
  246. if not os.path.exists(path):
  247. os.makedirs(path)
  248. f = open(filename, 'w')
  249. for hostname, keys in self.ssh._host_keys.iteritems():
  250. for keytype, key in keys.iteritems():
  251. # was f.write
  252. added_this_time = getattr(key, '_added_by_ansible_this_time', False)
  253. if not added_this_time:
  254. f.write("%s %s %s\n" % (hostname, keytype, key.get_base64()))
  255. for hostname, keys in self.ssh._host_keys.iteritems():
  256. for keytype, key in keys.iteritems():
  257. added_this_time = getattr(key, '_added_by_ansible_this_time', False)
  258. if added_this_time:
  259. f.write("%s %s %s\n" % (hostname, keytype, key.get_base64()))
  260. f.close()
  261. def close(self):
  262. ''' terminate the connection '''
  263. cache_key = self._cache_key()
  264. SSH_CONNECTION_CACHE.pop(cache_key, None)
  265. SFTP_CONNECTION_CACHE.pop(cache_key, None)
  266. if self.sftp is not None:
  267. self.sftp.close()
  268. if C.PARAMIKO_RECORD_HOST_KEYS and self._any_keys_added():
  269. # add any new SSH host keys -- warning -- this could be slow
  270. lockfile = self.keyfile.replace("known_hosts",".known_hosts.lock")
  271. dirname = os.path.dirname(self.keyfile)
  272. if not os.path.exists(dirname):
  273. os.makedirs(dirname)
  274. KEY_LOCK = open(lockfile, 'w')
  275. fcntl.lockf(KEY_LOCK, fcntl.LOCK_EX)
  276. try:
  277. # just in case any were added recently
  278. self.ssh.load_system_host_keys()
  279. self.ssh._host_keys.update(self.ssh._system_host_keys)
  280. self._save_ssh_host_keys(self.keyfile)
  281. except:
  282. # unable to save keys, including scenario when key was invalid
  283. # and caught earlier
  284. traceback.print_exc()
  285. pass
  286. fcntl.lockf(KEY_LOCK, fcntl.LOCK_UN)
  287. self.ssh.close()