Playbooks to a new Lilik
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1279 lines
55 KiB

  1. # Copyright (c) 2012, Michael DeHaan <michael.dehaan@gmail.com>
  2. # Copyright 2015 Abhijit Menon-Sen <ams@2ndQuadrant.com>
  3. # Copyright 2017 Toshio Kuratomi <tkuratomi@ansible.com>
  4. # Copyright (c) 2017 Ansible Project
  5. # Copyright 2020 Lorenzo Zolfanelli <lorenzo.zolfanelli@gmail.com>
  6. #
  7. # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
  8. from __future__ import (absolute_import, division, print_function)
  9. __metaclass__ = type
  10. DOCUMENTATION = '''
  11. connection: ssh_lxc
  12. short_description: connect via ssh client binary and then to a container with lxc-attach
  13. description:
  14. - This connection plugin allows ansible to communicate to the target machines via normal ssh command line.
  15. - Ansible does not expose a channel to allow communication between the user and the ssh process to accept
  16. a password manually to decrypt an ssh key when using this connection plugin (which is the default). The
  17. use of ``ssh-agent`` is highly recommended.
  18. author: Lorenzo Zolfanelli
  19. version_added: "2.9.6"
  20. options:
  21. host:
  22. description: Hostname/ip to connect to.
  23. default: inventory_hostname
  24. vars:
  25. - name: ansible_host
  26. - name: ansible_ssh_host
  27. container_name:
  28. description: name of lxc container to attach to
  29. vars:
  30. - name: ansible_ssh_lxc_name
  31. - name: ansible_docker_extra_args
  32. type: str
  33. host_key_checking:
  34. description: Determines if ssh should check host keys
  35. type: boolean
  36. ini:
  37. - section: defaults
  38. key: 'host_key_checking'
  39. - section: ssh_connection
  40. key: 'host_key_checking'
  41. version_added: '2.5'
  42. env:
  43. - name: ANSIBLE_HOST_KEY_CHECKING
  44. - name: ANSIBLE_SSH_HOST_KEY_CHECKING
  45. version_added: '2.5'
  46. vars:
  47. - name: ansible_host_key_checking
  48. version_added: '2.5'
  49. - name: ansible_ssh_host_key_checking
  50. version_added: '2.5'
  51. password:
  52. description: Authentication password for the C(remote_user). Can be supplied as CLI option.
  53. vars:
  54. - name: ansible_password
  55. - name: ansible_ssh_pass
  56. - name: ansible_ssh_password
  57. ssh_args:
  58. description: Arguments to pass to all ssh cli tools
  59. default: '-C -o ControlMaster=auto -o ControlPersist=60s'
  60. ini:
  61. - section: 'ssh_connection'
  62. key: 'ssh_args'
  63. env:
  64. - name: ANSIBLE_SSH_ARGS
  65. vars:
  66. - name: ansible_ssh_args
  67. version_added: '2.7'
  68. ssh_common_args:
  69. description: Common extra args for all ssh CLI tools
  70. ini:
  71. - section: 'ssh_connection'
  72. key: 'ssh_common_args'
  73. version_added: '2.7'
  74. env:
  75. - name: ANSIBLE_SSH_COMMON_ARGS
  76. version_added: '2.7'
  77. vars:
  78. - name: ansible_ssh_common_args
  79. ssh_executable:
  80. default: ssh
  81. description:
  82. - This defines the location of the ssh binary. It defaults to ``ssh`` which will use the first ssh binary available in $PATH.
  83. - This option is usually not required, it might be useful when access to system ssh is restricted,
  84. or when using ssh wrappers to connect to remote hosts.
  85. env: [{name: ANSIBLE_SSH_EXECUTABLE}]
  86. ini:
  87. - {key: ssh_executable, section: ssh_connection}
  88. #const: ANSIBLE_SSH_EXECUTABLE
  89. version_added: "2.2"
  90. vars:
  91. - name: ansible_ssh_executable
  92. version_added: '2.7'
  93. sftp_executable:
  94. default: sftp
  95. description:
  96. - This defines the location of the sftp binary. It defaults to ``sftp`` which will use the first binary available in $PATH.
  97. env: [{name: ANSIBLE_SFTP_EXECUTABLE}]
  98. ini:
  99. - {key: sftp_executable, section: ssh_connection}
  100. version_added: "2.6"
  101. vars:
  102. - name: ansible_sftp_executable
  103. version_added: '2.7'
  104. scp_executable:
  105. default: scp
  106. description:
  107. - This defines the location of the scp binary. It defaults to `scp` which will use the first binary available in $PATH.
  108. env: [{name: ANSIBLE_SCP_EXECUTABLE}]
  109. ini:
  110. - {key: scp_executable, section: ssh_connection}
  111. version_added: "2.6"
  112. vars:
  113. - name: ansible_scp_executable
  114. version_added: '2.7'
  115. scp_extra_args:
  116. description: Extra exclusive to the ``scp`` CLI
  117. vars:
  118. - name: ansible_scp_extra_args
  119. env:
  120. - name: ANSIBLE_SCP_EXTRA_ARGS
  121. version_added: '2.7'
  122. ini:
  123. - key: scp_extra_args
  124. section: ssh_connection
  125. version_added: '2.7'
  126. sftp_extra_args:
  127. description: Extra exclusive to the ``sftp`` CLI
  128. vars:
  129. - name: ansible_sftp_extra_args
  130. env:
  131. - name: ANSIBLE_SFTP_EXTRA_ARGS
  132. version_added: '2.7'
  133. ini:
  134. - key: sftp_extra_args
  135. section: ssh_connection
  136. version_added: '2.7'
  137. ssh_extra_args:
  138. description: Extra exclusive to the 'ssh' CLI
  139. vars:
  140. - name: ansible_ssh_extra_args
  141. env:
  142. - name: ANSIBLE_SSH_EXTRA_ARGS
  143. version_added: '2.7'
  144. ini:
  145. - key: ssh_extra_args
  146. section: ssh_connection
  147. version_added: '2.7'
  148. retries:
  149. # constant: ANSIBLE_SSH_RETRIES
  150. description: Number of attempts to connect.
  151. default: 3
  152. type: integer
  153. env:
  154. - name: ANSIBLE_SSH_RETRIES
  155. ini:
  156. - section: connection
  157. key: retries
  158. - section: ssh_connection
  159. key: retries
  160. vars:
  161. - name: ansible_ssh_retries
  162. version_added: '2.7'
  163. port:
  164. description: Remote port to connect to.
  165. type: int
  166. default: 22
  167. ini:
  168. - section: defaults
  169. key: remote_port
  170. env:
  171. - name: ANSIBLE_REMOTE_PORT
  172. vars:
  173. - name: ansible_port
  174. - name: ansible_ssh_port
  175. remote_user:
  176. description:
  177. - User name with which to login to the remote server, normally set by the remote_user keyword.
  178. - If no user is supplied, Ansible will let the ssh client binary choose the user as it normally
  179. ini:
  180. - section: defaults
  181. key: remote_user
  182. env:
  183. - name: ANSIBLE_REMOTE_USER
  184. vars:
  185. - name: ansible_user
  186. - name: ansible_ssh_user
  187. pipelining:
  188. default: ANSIBLE_PIPELINING
  189. description:
  190. - Pipelining reduces the number of SSH operations required to execute a module on the remote server,
  191. by executing many Ansible modules without actual file transfer.
  192. - This can result in a very significant performance improvement when enabled.
  193. - However this conflicts with privilege escalation (become).
  194. For example, when using sudo operations you must first disable 'requiretty' in the sudoers file for the target hosts,
  195. which is why this feature is disabled by default.
  196. env:
  197. - name: ANSIBLE_PIPELINING
  198. #- name: ANSIBLE_SSH_PIPELINING
  199. ini:
  200. - section: defaults
  201. key: pipelining
  202. #- section: ssh_connection
  203. # key: pipelining
  204. type: boolean
  205. vars:
  206. - name: ansible_pipelining
  207. - name: ansible_ssh_pipelining
  208. private_key_file:
  209. description:
  210. - Path to private key file to use for authentication
  211. ini:
  212. - section: defaults
  213. key: private_key_file
  214. env:
  215. - name: ANSIBLE_PRIVATE_KEY_FILE
  216. vars:
  217. - name: ansible_private_key_file
  218. - name: ansible_ssh_private_key_file
  219. control_path:
  220. description:
  221. - This is the location to save ssh's ControlPath sockets, it uses ssh's variable substitution.
  222. - Since 2.3, if null, ansible will generate a unique hash. Use `%(directory)s` to indicate where to use the control dir path setting.
  223. env:
  224. - name: ANSIBLE_SSH_CONTROL_PATH
  225. ini:
  226. - key: control_path
  227. section: ssh_connection
  228. vars:
  229. - name: ansible_control_path
  230. version_added: '2.7'
  231. control_path_dir:
  232. default: ~/.ansible/cp
  233. description:
  234. - This sets the directory to use for ssh control path if the control path setting is null.
  235. - Also, provides the `%(directory)s` variable for the control path setting.
  236. env:
  237. - name: ANSIBLE_SSH_CONTROL_PATH_DIR
  238. ini:
  239. - section: ssh_connection
  240. key: control_path_dir
  241. vars:
  242. - name: ansible_control_path_dir
  243. version_added: '2.7'
  244. sftp_batch_mode:
  245. default: 'yes'
  246. description: 'TODO: write it'
  247. env: [{name: ANSIBLE_SFTP_BATCH_MODE}]
  248. ini:
  249. - {key: sftp_batch_mode, section: ssh_connection}
  250. type: bool
  251. vars:
  252. - name: ansible_sftp_batch_mode
  253. version_added: '2.7'
  254. scp_if_ssh:
  255. default: smart
  256. description:
  257. - "Prefered method to use when transfering files over ssh"
  258. - When set to smart, Ansible will try them until one succeeds or they all fail
  259. - If set to True, it will force 'scp', if False it will use 'sftp'
  260. env: [{name: ANSIBLE_SCP_IF_SSH}]
  261. ini:
  262. - {key: scp_if_ssh, section: ssh_connection}
  263. vars:
  264. - name: ansible_scp_if_ssh
  265. version_added: '2.7'
  266. use_tty:
  267. version_added: '2.5'
  268. default: 'yes'
  269. description: add -tt to ssh commands to force tty allocation
  270. env: [{name: ANSIBLE_SSH_USETTY}]
  271. ini:
  272. - {key: usetty, section: ssh_connection}
  273. type: bool
  274. vars:
  275. - name: ansible_ssh_use_tty
  276. version_added: '2.7'
  277. '''
  278. import errno
  279. import fcntl
  280. import hashlib
  281. import os
  282. import pty
  283. import re
  284. import subprocess
  285. import time
  286. from functools import wraps
  287. from ansible import constants as C
  288. from ansible.errors import (
  289. AnsibleAuthenticationFailure,
  290. AnsibleConnectionFailure,
  291. AnsibleError,
  292. AnsibleFileNotFound,
  293. )
  294. from ansible.errors import AnsibleOptionsError
  295. from ansible.compat import selectors
  296. from ansible.module_utils.six import PY3, text_type, binary_type
  297. from ansible.module_utils.six.moves import shlex_quote
  298. from ansible.module_utils._text import to_bytes, to_native, to_text
  299. from ansible.module_utils.parsing.convert_bool import BOOLEANS, boolean
  300. from ansible.plugins.connection import ConnectionBase, BUFSIZE
  301. from ansible.plugins.shell.powershell import _parse_clixml
  302. from ansible.utils.display import Display
  303. from ansible.utils.path import unfrackpath, makedirs_safe
  304. display = Display()
  305. b_NOT_SSH_ERRORS = (b'Traceback (most recent call last):', # Python-2.6 when there's an exception
  306. # while invoking a script via -m
  307. b'PHP Parse error:', # Php always returns error 255
  308. )
  309. SSHPASS_AVAILABLE = None
  310. class AnsibleControlPersistBrokenPipeError(AnsibleError):
  311. ''' ControlPersist broken pipe '''
  312. pass
  313. def _handle_error(remaining_retries, command, return_tuple, no_log, host, display=display):
  314. # sshpass errors
  315. if command == b'sshpass':
  316. # Error 5 is invalid/incorrect password. Raise an exception to prevent retries from locking the account.
  317. if return_tuple[0] == 5:
  318. msg = 'Invalid/incorrect username/password. Skipping remaining {0} retries to prevent account lockout:'.format(remaining_retries)
  319. if remaining_retries <= 0:
  320. msg = 'Invalid/incorrect password:'
  321. if no_log:
  322. msg = '{0} <error censored due to no log>'.format(msg)
  323. else:
  324. msg = '{0} {1}'.format(msg, to_native(return_tuple[2]).rstrip())
  325. raise AnsibleAuthenticationFailure(msg)
  326. # sshpass returns codes are 1-6. We handle 5 previously, so this catches other scenarios.
  327. # No exception is raised, so the connection is retried.
  328. elif return_tuple[0] in [1, 2, 3, 4, 6]:
  329. msg = 'sshpass error:'
  330. if no_log:
  331. msg = '{0} <error censored due to no log>'.format(msg)
  332. else:
  333. msg = '{0} {1}'.format(msg, to_native(return_tuple[2]).rstrip())
  334. if return_tuple[0] == 255:
  335. SSH_ERROR = True
  336. for signature in b_NOT_SSH_ERRORS:
  337. if signature in return_tuple[1]:
  338. SSH_ERROR = False
  339. break
  340. if SSH_ERROR:
  341. msg = "Failed to connect to the host via ssh:"
  342. if no_log:
  343. msg = '{0} <error censored due to no log>'.format(msg)
  344. else:
  345. msg = '{0} {1}'.format(msg, to_native(return_tuple[2]).rstrip())
  346. raise AnsibleConnectionFailure(msg)
  347. # For other errors, no execption is raised so the connection is retried and we only log the messages
  348. if 1 <= return_tuple[0] <= 254:
  349. msg = u"Failed to connect to the host via ssh:"
  350. if no_log:
  351. msg = u'{0} <error censored due to no log>'.format(msg)
  352. else:
  353. msg = u'{0} {1}'.format(msg, to_text(return_tuple[2]).rstrip())
  354. display.vvv(msg, host=host)
  355. def _ssh_retry(func):
  356. """
  357. Decorator to retry ssh/scp/sftp in the case of a connection failure
  358. Will retry if:
  359. * an exception is caught
  360. * ssh returns 255
  361. Will not retry if
  362. * sshpass returns 5 (invalid password, to prevent account lockouts)
  363. * remaining_tries is < 2
  364. * retries limit reached
  365. """
  366. @wraps(func)
  367. def wrapped(self, *args, **kwargs):
  368. remaining_tries = int(C.ANSIBLE_SSH_RETRIES) + 1
  369. cmd_summary = u"%s..." % to_text(args[0])
  370. for attempt in range(remaining_tries):
  371. cmd = args[0]
  372. if attempt != 0 and self._play_context.password and isinstance(cmd, list):
  373. # If this is a retry, the fd/pipe for sshpass is closed, and we need a new one
  374. self.sshpass_pipe = os.pipe()
  375. cmd[1] = b'-d' + to_bytes(self.sshpass_pipe[0], nonstring='simplerepr', errors='surrogate_or_strict')
  376. try:
  377. try:
  378. return_tuple = func(self, *args, **kwargs)
  379. if self._play_context.no_log:
  380. display.vvv(u'rc=%s, stdout and stderr censored due to no log' % return_tuple[0], host=self.host)
  381. else:
  382. display.vvv(return_tuple, host=self.host)
  383. # 0 = success
  384. # 1-254 = remote command return code
  385. # 255 could be a failure from the ssh command itself
  386. except (AnsibleControlPersistBrokenPipeError):
  387. # Retry one more time because of the ControlPersist broken pipe (see #16731)
  388. cmd = args[0]
  389. if self._play_context.password and isinstance(cmd, list):
  390. # This is a retry, so the fd/pipe for sshpass is closed, and we need a new one
  391. self.sshpass_pipe = os.pipe()
  392. cmd[1] = b'-d' + to_bytes(self.sshpass_pipe[0], nonstring='simplerepr', errors='surrogate_or_strict')
  393. display.vvv(u"RETRYING BECAUSE OF CONTROLPERSIST BROKEN PIPE")
  394. return_tuple = func(self, *args, **kwargs)
  395. remaining_retries = remaining_tries - attempt - 1
  396. _handle_error(remaining_retries, cmd[0], return_tuple, self._play_context.no_log, self.host)
  397. break
  398. # 5 = Invalid/incorrect password from sshpass
  399. except AnsibleAuthenticationFailure:
  400. # Raising this exception, which is subclassed from AnsibleConnectionFailure, prevents further retries
  401. raise
  402. except (AnsibleConnectionFailure, Exception) as e:
  403. if attempt == remaining_tries - 1:
  404. raise
  405. else:
  406. pause = 2 ** attempt - 1
  407. if pause > 30:
  408. pause = 30
  409. if isinstance(e, AnsibleConnectionFailure):
  410. msg = u"ssh_retry: attempt: %d, ssh return code is 255. cmd (%s), pausing for %d seconds" % (attempt + 1, cmd_summary, pause)
  411. else:
  412. msg = (u"ssh_retry: attempt: %d, caught exception(%s) from cmd (%s), "
  413. u"pausing for %d seconds" % (attempt + 1, to_text(e), cmd_summary, pause))
  414. display.vv(msg, host=self.host)
  415. time.sleep(pause)
  416. continue
  417. return return_tuple
  418. return wrapped
  419. class Connection(ConnectionBase):
  420. ''' ssh based connections '''
  421. transport = 'ssh_lxc'
  422. has_pipelining = True
  423. def __init__(self, *args, **kwargs):
  424. super(Connection, self).__init__(*args, **kwargs)
  425. self.host = self._play_context.remote_addr
  426. self.port = self._play_context.port
  427. self.user = self._play_context.remote_user
  428. self.control_path = C.ANSIBLE_SSH_CONTROL_PATH
  429. self.control_path_dir = C.ANSIBLE_SSH_CONTROL_PATH_DIR
  430. # Windows operates differently from a POSIX connection/shell plugin,
  431. # we need to set various properties to ensure SSH on Windows continues
  432. # to work
  433. if getattr(self._shell, "_IS_WINDOWS", False):
  434. self.has_native_async = True
  435. self.always_pipeline_modules = True
  436. self.module_implementation_preferences = ('.ps1', '.exe', '')
  437. self.allow_executable = False
  438. # The connection is created by running ssh/scp/sftp from the exec_command,
  439. # put_file, and fetch_file methods, so we don't need to do any connection
  440. # management here.
  441. def _connect(self):
  442. self.container_name = self.get_option('container_name')
  443. return self
  444. @staticmethod
  445. def _create_control_path(host, port, user, connection=None, pid=None):
  446. '''Make a hash for the controlpath based on con attributes'''
  447. pstring = '%s-%s-%s' % (host, port, user)
  448. if connection:
  449. pstring += '-%s' % connection
  450. if pid:
  451. pstring += '-%s' % to_text(pid)
  452. m = hashlib.sha1()
  453. m.update(to_bytes(pstring))
  454. digest = m.hexdigest()
  455. cpath = '%(directory)s/' + digest[:10]
  456. return cpath
  457. @staticmethod
  458. def _sshpass_available():
  459. global SSHPASS_AVAILABLE
  460. # We test once if sshpass is available, and remember the result. It
  461. # would be nice to use distutils.spawn.find_executable for this, but
  462. # distutils isn't always available; shutils.which() is Python3-only.
  463. if SSHPASS_AVAILABLE is None:
  464. try:
  465. p = subprocess.Popen(["sshpass"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  466. p.communicate()
  467. SSHPASS_AVAILABLE = True
  468. except OSError:
  469. SSHPASS_AVAILABLE = False
  470. return SSHPASS_AVAILABLE
  471. @staticmethod
  472. def _persistence_controls(b_command):
  473. '''
  474. Takes a command array and scans it for ControlPersist and ControlPath
  475. settings and returns two booleans indicating whether either was found.
  476. This could be smarter, e.g. returning false if ControlPersist is 'no',
  477. but for now we do it simple way.
  478. '''
  479. controlpersist = False
  480. controlpath = False
  481. for b_arg in (a.lower() for a in b_command):
  482. if b'controlpersist' in b_arg:
  483. controlpersist = True
  484. elif b'controlpath' in b_arg:
  485. controlpath = True
  486. return controlpersist, controlpath
  487. def _add_args(self, b_command, b_args, explanation):
  488. """
  489. Adds arguments to the ssh command and displays a caller-supplied explanation of why.
  490. :arg b_command: A list containing the command to add the new arguments to.
  491. This list will be modified by this method.
  492. :arg b_args: An iterable of new arguments to add. This iterable is used
  493. more than once so it must be persistent (ie: a list is okay but a
  494. StringIO would not)
  495. :arg explanation: A text string containing explaining why the arguments
  496. were added. It will be displayed with a high enough verbosity.
  497. .. note:: This function does its work via side-effect. The b_command list has the new arguments appended.
  498. """
  499. display.vvvvv(u'SSH: %s: (%s)' % (explanation, ')('.join(to_text(a) for a in b_args)), host=self._play_context.remote_addr)
  500. b_command += b_args
  501. def _build_command(self, binary, *other_args):
  502. '''
  503. Takes a binary (ssh, scp, sftp) and optional extra arguments and returns
  504. a command line as an array that can be passed to subprocess.Popen.
  505. '''
  506. b_command = []
  507. #
  508. # First, the command to invoke
  509. #
  510. # If we want to use password authentication, we have to set up a pipe to
  511. # write the password to sshpass.
  512. if self._play_context.password:
  513. if not self._sshpass_available():
  514. raise AnsibleError("to use the 'ssh' connection type with passwords, you must install the sshpass program")
  515. self.sshpass_pipe = os.pipe()
  516. b_command += [b'sshpass', b'-d' + to_bytes(self.sshpass_pipe[0], nonstring='simplerepr', errors='surrogate_or_strict')]
  517. if binary == 'ssh':
  518. b_command += [to_bytes(self._play_context.ssh_executable, errors='surrogate_or_strict')]
  519. else:
  520. b_command += [to_bytes(binary, errors='surrogate_or_strict')]
  521. #
  522. # Next, additional arguments based on the configuration.
  523. #
  524. # sftp batch mode allows us to correctly catch failed transfers, but can
  525. # be disabled if the client side doesn't support the option. However,
  526. # sftp batch mode does not prompt for passwords so it must be disabled
  527. # if not using controlpersist and using sshpass
  528. if binary == 'sftp' and C.DEFAULT_SFTP_BATCH_MODE:
  529. if self._play_context.password:
  530. b_args = [b'-o', b'BatchMode=no']
  531. self._add_args(b_command, b_args, u'disable batch mode for sshpass')
  532. b_command += [b'-b', b'-']
  533. if self._play_context.verbosity > 3:
  534. b_command.append(b'-vvv')
  535. #
  536. # Next, we add [ssh_connection]ssh_args from ansible.cfg.
  537. #
  538. if self._play_context.ssh_args:
  539. b_args = [to_bytes(a, errors='surrogate_or_strict') for a in
  540. self._split_ssh_args(self._play_context.ssh_args)]
  541. self._add_args(b_command, b_args, u"ansible.cfg set ssh_args")
  542. # Now we add various arguments controlled by configuration file settings
  543. # (e.g. host_key_checking) or inventory variables (ansible_ssh_port) or
  544. # a combination thereof.
  545. if not C.HOST_KEY_CHECKING:
  546. b_args = (b"-o", b"StrictHostKeyChecking=no")
  547. self._add_args(b_command, b_args, u"ANSIBLE_HOST_KEY_CHECKING/host_key_checking disabled")
  548. if self._play_context.port is not None:
  549. b_args = (b"-o", b"Port=" + to_bytes(self._play_context.port, nonstring='simplerepr', errors='surrogate_or_strict'))
  550. self._add_args(b_command, b_args, u"ANSIBLE_REMOTE_PORT/remote_port/ansible_port set")
  551. key = self._play_context.private_key_file
  552. if key:
  553. b_args = (b"-o", b'IdentityFile="' + to_bytes(os.path.expanduser(key), errors='surrogate_or_strict') + b'"')
  554. self._add_args(b_command, b_args, u"ANSIBLE_PRIVATE_KEY_FILE/private_key_file/ansible_ssh_private_key_file set")
  555. if not self._play_context.password:
  556. self._add_args(
  557. b_command, (
  558. b"-o", b"KbdInteractiveAuthentication=no",
  559. b"-o", b"PreferredAuthentications=gssapi-with-mic,gssapi-keyex,hostbased,publickey",
  560. b"-o", b"PasswordAuthentication=no"
  561. ),
  562. u"ansible_password/ansible_ssh_password not set"
  563. )
  564. user = self._play_context.remote_user
  565. if user:
  566. self._add_args(
  567. b_command,
  568. (b"-o", b'User="%s"' % to_bytes(self._play_context.remote_user, errors='surrogate_or_strict')),
  569. u"ANSIBLE_REMOTE_USER/remote_user/ansible_user/user/-u set"
  570. )
  571. self._add_args(
  572. b_command,
  573. (b"-o", b"ConnectTimeout=" + to_bytes(self._play_context.timeout, errors='surrogate_or_strict', nonstring='simplerepr')),
  574. u"ANSIBLE_TIMEOUT/timeout set"
  575. )
  576. # Add in any common or binary-specific arguments from the PlayContext
  577. # (i.e. inventory or task settings or overrides on the command line).
  578. for opt in (u'ssh_common_args', u'{0}_extra_args'.format(binary)):
  579. attr = getattr(self._play_context, opt, None)
  580. if attr is not None:
  581. b_args = [to_bytes(a, errors='surrogate_or_strict') for a in self._split_ssh_args(attr)]
  582. self._add_args(b_command, b_args, u"PlayContext set %s" % opt)
  583. # Check if ControlPersist is enabled and add a ControlPath if one hasn't
  584. # already been set.
  585. controlpersist, controlpath = self._persistence_controls(b_command)
  586. if controlpersist:
  587. self._persistent = True
  588. if not controlpath:
  589. cpdir = unfrackpath(self.control_path_dir)
  590. b_cpdir = to_bytes(cpdir, errors='surrogate_or_strict')
  591. # The directory must exist and be writable.
  592. makedirs_safe(b_cpdir, 0o700)
  593. if not os.access(b_cpdir, os.W_OK):
  594. raise AnsibleError("Cannot write to ControlPath %s" % to_native(cpdir))
  595. if not self.control_path:
  596. self.control_path = self._create_control_path(
  597. self.host,
  598. self.port,
  599. self.user
  600. )
  601. b_args = (b"-o", b"ControlPath=" + to_bytes(self.control_path % dict(directory=cpdir), errors='surrogate_or_strict'))
  602. self._add_args(b_command, b_args, u"found only ControlPersist; added ControlPath")
  603. # Finally, we add any caller-supplied extras.
  604. if other_args:
  605. b_command += [to_bytes(a) for a in other_args]
  606. return b_command
  607. def _send_initial_data(self, fh, in_data, ssh_process):
  608. '''
  609. Writes initial data to the stdin filehandle of the subprocess and closes
  610. it. (The handle must be closed; otherwise, for example, "sftp -b -" will
  611. just hang forever waiting for more commands.)
  612. '''
  613. display.debug(u'Sending initial data')
  614. try:
  615. fh.write(to_bytes(in_data))
  616. fh.close()
  617. except (OSError, IOError) as e:
  618. # The ssh connection may have already terminated at this point, with a more useful error
  619. # Only raise AnsibleConnectionFailure if the ssh process is still alive
  620. time.sleep(0.001)
  621. ssh_process.poll()
  622. if getattr(ssh_process, 'returncode', None) is None:
  623. raise AnsibleConnectionFailure(
  624. 'Data could not be sent to remote host "%s". Make sure this host can be reached '
  625. 'over ssh: %s' % (self.host, to_native(e)), orig_exc=e
  626. )
  627. display.debug(u'Sent initial data (%d bytes)' % len(in_data))
  628. # Used by _run() to kill processes on failures
  629. @staticmethod
  630. def _terminate_process(p):
  631. """ Terminate a process, ignoring errors """
  632. try:
  633. p.terminate()
  634. except (OSError, IOError):
  635. pass
  636. # This is separate from _run() because we need to do the same thing for stdout
  637. # and stderr.
  638. def _examine_output(self, source, state, b_chunk, sudoable):
  639. '''
  640. Takes a string, extracts complete lines from it, tests to see if they
  641. are a prompt, error message, etc., and sets appropriate flags in self.
  642. Prompt and success lines are removed.
  643. Returns the processed (i.e. possibly-edited) output and the unprocessed
  644. remainder (to be processed with the next chunk) as strings.
  645. '''
  646. output = []
  647. for b_line in b_chunk.splitlines(True):
  648. display_line = to_text(b_line).rstrip('\r\n')
  649. suppress_output = False
  650. # display.debug("Examining line (source=%s, state=%s): '%s'" % (source, state, display_line))
  651. if self.become.expect_prompt() and self.become.check_password_prompt(b_line):
  652. display.debug(u"become_prompt: (source=%s, state=%s): '%s'" % (source, state, display_line))
  653. self._flags['become_prompt'] = True
  654. suppress_output = True
  655. elif self.become.success and self.become.check_success(b_line):
  656. display.debug(u"become_success: (source=%s, state=%s): '%s'" % (source, state, display_line))
  657. self._flags['become_success'] = True
  658. suppress_output = True
  659. elif sudoable and self.become.check_incorrect_password(b_line):
  660. display.debug(u"become_error: (source=%s, state=%s): '%s'" % (source, state, display_line))
  661. self._flags['become_error'] = True
  662. elif sudoable and self.become.check_missing_password(b_line):
  663. display.debug(u"become_nopasswd_error: (source=%s, state=%s): '%s'" % (source, state, display_line))
  664. self._flags['become_nopasswd_error'] = True
  665. if not suppress_output:
  666. output.append(b_line)
  667. # The chunk we read was most likely a series of complete lines, but just
  668. # in case the last line was incomplete (and not a prompt, which we would
  669. # have removed from the output), we retain it to be processed with the
  670. # next chunk.
  671. remainder = b''
  672. if output and not output[-1].endswith(b'\n'):
  673. remainder = output[-1]
  674. output = output[:-1]
  675. return b''.join(output), remainder
  676. def _bare_run(self, cmd, in_data, sudoable=True, checkrc=True):
  677. '''
  678. Starts the command and communicates with it until it ends.
  679. '''
  680. # We don't use _shell.quote as this is run on the controller and independent from the shell plugin chosen
  681. display_cmd = u' '.join(shlex_quote(to_text(c)) for c in cmd)
  682. display.vvv(u'SSH_LXC: EXEC {0}'.format(display_cmd), host=self.host)
  683. # Start the given command. If we don't need to pipeline data, we can try
  684. # to use a pseudo-tty (ssh will have been invoked with -tt). If we are
  685. # pipelining data, or can't create a pty, we fall back to using plain
  686. # old pipes.
  687. p = None
  688. if isinstance(cmd, (text_type, binary_type)):
  689. cmd = to_bytes(cmd)
  690. else:
  691. cmd = list(map(to_bytes, cmd))
  692. if not in_data:
  693. try:
  694. # Make sure stdin is a proper pty to avoid tcgetattr errors
  695. master, slave = pty.openpty()
  696. if PY3 and self._play_context.password:
  697. # pylint: disable=unexpected-keyword-arg
  698. p = subprocess.Popen(cmd, stdin=slave, stdout=subprocess.PIPE, stderr=subprocess.PIPE, pass_fds=self.sshpass_pipe)
  699. else:
  700. p = subprocess.Popen(cmd, stdin=slave, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  701. stdin = os.fdopen(master, 'wb', 0)
  702. os.close(slave)
  703. except (OSError, IOError):
  704. p = None
  705. if not p:
  706. if PY3 and self._play_context.password:
  707. # pylint: disable=unexpected-keyword-arg
  708. p = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, pass_fds=self.sshpass_pipe)
  709. else:
  710. p = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  711. stdin = p.stdin
  712. # If we are using SSH password authentication, write the password into
  713. # the pipe we opened in _build_command.
  714. if self._play_context.password:
  715. os.close(self.sshpass_pipe[0])
  716. try:
  717. os.write(self.sshpass_pipe[1], to_bytes(self._play_context.password) + b'\n')
  718. except OSError as e:
  719. # Ignore broken pipe errors if the sshpass process has exited.
  720. if e.errno != errno.EPIPE or p.poll() is None:
  721. raise
  722. os.close(self.sshpass_pipe[1])
  723. #
  724. # SSH state machine
  725. #
  726. # Now we read and accumulate output from the running process until it
  727. # exits. Depending on the circumstances, we may also need to write an
  728. # escalation password and/or pipelined input to the process.
  729. states = [
  730. 'awaiting_prompt', 'awaiting_escalation', 'ready_to_send', 'awaiting_exit'
  731. ]
  732. # Are we requesting privilege escalation? Right now, we may be invoked
  733. # to execute sftp/scp with sudoable=True, but we can request escalation
  734. # only when using ssh. Otherwise we can send initial data straightaway.
  735. state = states.index('ready_to_send')
  736. if to_bytes(self.get_option('ssh_executable')) in cmd and sudoable:
  737. prompt = getattr(self.become, 'prompt', None)
  738. if prompt:
  739. # We're requesting escalation with a password, so we have to
  740. # wait for a password prompt.
  741. state = states.index('awaiting_prompt')
  742. display.debug(u'Initial state: %s: %s' % (states[state], to_text(prompt)))
  743. elif self.become and self.become.success:
  744. # We're requesting escalation without a password, so we have to
  745. # detect success/failure before sending any initial data.
  746. state = states.index('awaiting_escalation')
  747. display.debug(u'Initial state: %s: %s' % (states[state], to_text(self.become.success)))
  748. # We store accumulated stdout and stderr output from the process here,
  749. # but strip any privilege escalation prompt/confirmation lines first.
  750. # Output is accumulated into tmp_*, complete lines are extracted into
  751. # an array, then checked and removed or copied to stdout or stderr. We
  752. # set any flags based on examining the output in self._flags.
  753. b_stdout = b_stderr = b''
  754. b_tmp_stdout = b_tmp_stderr = b''
  755. self._flags = dict(
  756. become_prompt=False, become_success=False,
  757. become_error=False, become_nopasswd_error=False
  758. )
  759. # select timeout should be longer than the connect timeout, otherwise
  760. # they will race each other when we can't connect, and the connect
  761. # timeout usually fails
  762. timeout = 2 + self._play_context.timeout
  763. for fd in (p.stdout, p.stderr):
  764. fcntl.fcntl(fd, fcntl.F_SETFL, fcntl.fcntl(fd, fcntl.F_GETFL) | os.O_NONBLOCK)
  765. # TODO: bcoca would like to use SelectSelector() when open
  766. # filehandles is low, then switch to more efficient ones when higher.
  767. # select is faster when filehandles is low.
  768. selector = selectors.DefaultSelector()
  769. selector.register(p.stdout, selectors.EVENT_READ)
  770. selector.register(p.stderr, selectors.EVENT_READ)
  771. # If we can send initial data without waiting for anything, we do so
  772. # before we start polling
  773. if states[state] == 'ready_to_send' and in_data:
  774. self._send_initial_data(stdin, in_data, p)
  775. state += 1
  776. try:
  777. while True:
  778. poll = p.poll()
  779. events = selector.select(timeout)
  780. # We pay attention to timeouts only while negotiating a prompt.
  781. if not events:
  782. # We timed out
  783. if state <= states.index('awaiting_escalation'):
  784. # If the process has already exited, then it's not really a
  785. # timeout; we'll let the normal error handling deal with it.
  786. if poll is not None:
  787. break
  788. self._terminate_process(p)
  789. raise AnsibleError('Timeout (%ds) waiting for privilege escalation prompt: %s' % (timeout, to_native(b_stdout)))
  790. # Read whatever output is available on stdout and stderr, and stop
  791. # listening to the pipe if it's been closed.
  792. for key, event in events:
  793. if key.fileobj == p.stdout:
  794. b_chunk = p.stdout.read()
  795. if b_chunk == b'':
  796. # stdout has been closed, stop watching it
  797. selector.unregister(p.stdout)
  798. # When ssh has ControlMaster (+ControlPath/Persist) enabled, the
  799. # first connection goes into the background and we never see EOF
  800. # on stderr. If we see EOF on stdout, lower the select timeout
  801. # to reduce the time wasted selecting on stderr if we observe
  802. # that the process has not yet existed after this EOF. Otherwise
  803. # we may spend a long timeout period waiting for an EOF that is
  804. # not going to arrive until the persisted connection closes.
  805. timeout = 1
  806. b_tmp_stdout += b_chunk
  807. display.debug(u"stdout chunk (state=%s):\n>>>%s<<<\n" % (state, to_text(b_chunk)))
  808. elif key.fileobj == p.stderr:
  809. b_chunk = p.stderr.read()
  810. if b_chunk == b'':
  811. # stderr has been closed, stop watching it
  812. selector.unregister(p.stderr)
  813. b_tmp_stderr += b_chunk
  814. display.debug("stderr chunk (state=%s):\n>>>%s<<<\n" % (state, to_text(b_chunk)))
  815. # We examine the output line-by-line until we have negotiated any
  816. # privilege escalation prompt and subsequent success/error message.
  817. # Afterwards, we can accumulate output without looking at it.
  818. if state < states.index('ready_to_send'):
  819. if b_tmp_stdout:
  820. b_output, b_unprocessed = self._examine_output('stdout', states[state], b_tmp_stdout, sudoable)
  821. b_stdout += b_output
  822. b_tmp_stdout = b_unprocessed
  823. if b_tmp_stderr:
  824. b_output, b_unprocessed = self._examine_output('stderr', states[state], b_tmp_stderr, sudoable)
  825. b_stderr += b_output
  826. b_tmp_stderr = b_unprocessed
  827. else:
  828. b_stdout += b_tmp_stdout
  829. b_stderr += b_tmp_stderr
  830. b_tmp_stdout = b_tmp_stderr = b''
  831. # If we see a privilege escalation prompt, we send the password.
  832. # (If we're expecting a prompt but the escalation succeeds, we
  833. # didn't need the password and can carry on regardless.)
  834. if states[state] == 'awaiting_prompt':
  835. if self._flags['become_prompt']:
  836. display.debug(u'Sending become_password in response to prompt')
  837. become_pass = self.become.get_option('become_pass', playcontext=self._play_context)
  838. stdin.write(to_bytes(become_pass, errors='surrogate_or_strict') + b'\n')
  839. # On python3 stdin is a BufferedWriter, and we don't have a guarantee
  840. # that the write will happen without a flush
  841. stdin.flush()
  842. self._flags['become_prompt'] = False
  843. state += 1
  844. elif self._flags['become_success']:
  845. state += 1
  846. # We've requested escalation (with or without a password), now we
  847. # wait for an error message or a successful escalation.
  848. if states[state] == 'awaiting_escalation':
  849. if self._flags['become_success']:
  850. display.vvv(u'Escalation succeeded')
  851. self._flags['become_success'] = False
  852. state += 1
  853. elif self._flags['become_error']:
  854. display.vvv(u'Escalation failed')
  855. self._terminate_process(p)
  856. self._flags['become_error'] = False
  857. raise AnsibleError('Incorrect %s password' % self.become.name)
  858. elif self._flags['become_nopasswd_error']:
  859. display.vvv(u'Escalation requires password')
  860. self._terminate_process(p)
  861. self._flags['become_nopasswd_error'] = False
  862. raise AnsibleError('Missing %s password' % self.become.name)
  863. elif self._flags['become_prompt']:
  864. # This shouldn't happen, because we should see the "Sorry,
  865. # try again" message first.
  866. display.vvv(u'Escalation prompt repeated')
  867. self._terminate_process(p)
  868. self._flags['become_prompt'] = False
  869. raise AnsibleError('Incorrect %s password' % self.become.name)
  870. # Once we're sure that the privilege escalation prompt, if any, has
  871. # been dealt with, we can send any initial data and start waiting
  872. # for output.
  873. if states[state] == 'ready_to_send':
  874. if in_data:
  875. self._send_initial_data(stdin, in_data, p)
  876. state += 1
  877. # Now we're awaiting_exit: has the child process exited? If it has,
  878. # and we've read all available output from it, we're done.
  879. if poll is not None:
  880. if not selector.get_map() or not events:
  881. break
  882. # We should not see further writes to the stdout/stderr file
  883. # descriptors after the process has closed, set the select
  884. # timeout to gather any last writes we may have missed.
  885. timeout = 0
  886. continue
  887. # If the process has not yet exited, but we've already read EOF from
  888. # its stdout and stderr (and thus no longer watching any file
  889. # descriptors), we can just wait for it to exit.
  890. elif not selector.get_map():
  891. p.wait()
  892. break
  893. # Otherwise there may still be outstanding data to read.
  894. finally:
  895. selector.close()
  896. # close stdin, stdout, and stderr after process is terminated and
  897. # stdout/stderr are read completely (see also issues #848, #64768).
  898. stdin.close()
  899. p.stdout.close()
  900. p.stderr.close()
  901. if C.HOST_KEY_CHECKING:
  902. if cmd[0] == b"sshpass" and p.returncode == 6:
  903. raise AnsibleError('Using a SSH password instead of a key is not possible because Host Key checking is enabled and sshpass does not support '
  904. 'this. Please add this host\'s fingerprint to your known_hosts file to manage this host.')
  905. controlpersisterror = b'Bad configuration option: ControlPersist' in b_stderr or b'unknown configuration option: ControlPersist' in b_stderr
  906. if p.returncode != 0 and controlpersisterror:
  907. raise AnsibleError('using -c ssh on certain older ssh versions may not support ControlPersist, set ANSIBLE_SSH_ARGS="" '
  908. '(or ssh_args in [ssh_connection] section of the config file) before running again')
  909. # If we find a broken pipe because of ControlPersist timeout expiring (see #16731),
  910. # we raise a special exception so that we can retry a connection.
  911. controlpersist_broken_pipe = b'mux_client_hello_exchange: write packet: Broken pipe' in b_stderr
  912. if p.returncode == 255:
  913. additional = to_native(b_stderr)
  914. if controlpersist_broken_pipe:
  915. raise AnsibleControlPersistBrokenPipeError('Data could not be sent because of ControlPersist broken pipe: %s' % additional)
  916. elif in_data and checkrc:
  917. raise AnsibleConnectionFailure('Data could not be sent to remote host "%s". Make sure this host can be reached over ssh: %s'
  918. % (self.host, additional))
  919. return (p.returncode, b_stdout, b_stderr)
  920. @_ssh_retry
  921. def _run(self, cmd, in_data, sudoable=True, checkrc=True):
  922. """Wrapper around _bare_run that retries the connection
  923. """
  924. return self._bare_run(cmd, in_data, sudoable=sudoable, checkrc=checkrc)
  925. @_ssh_retry
  926. def _file_transport_command(self, in_path, out_path, sftp_action):
  927. # scp and sftp require square brackets for IPv6 addresses, but
  928. # accept them for hostnames and IPv4 addresses too.
  929. host = '[%s]' % self.host
  930. smart_methods = ['sftp', 'scp', 'piped']
  931. # Windows does not support dd so we cannot use the piped method
  932. if getattr(self._shell, "_IS_WINDOWS", False):
  933. smart_methods.remove('piped')
  934. # Transfer methods to try
  935. methods = []
  936. # Use the transfer_method option if set, otherwise use scp_if_ssh
  937. ssh_transfer_method = self._play_context.ssh_transfer_method
  938. if ssh_transfer_method is not None:
  939. if not (ssh_transfer_method in ('smart', 'sftp', 'scp', 'piped')):
  940. raise AnsibleOptionsError('transfer_method needs to be one of [smart|sftp|scp|piped]')
  941. if ssh_transfer_method == 'smart':
  942. methods = smart_methods
  943. else:
  944. methods = [ssh_transfer_method]
  945. else:
  946. # since this can be a non-bool now, we need to handle it correctly
  947. scp_if_ssh = C.DEFAULT_SCP_IF_SSH
  948. if not isinstance(scp_if_ssh, bool):
  949. scp_if_ssh = scp_if_ssh.lower()
  950. if scp_if_ssh in BOOLEANS:
  951. scp_if_ssh = boolean(scp_if_ssh, strict=False)
  952. elif scp_if_ssh != 'smart':
  953. raise AnsibleOptionsError('scp_if_ssh needs to be one of [smart|True|False]')
  954. if scp_if_ssh == 'smart':
  955. methods = smart_methods
  956. elif scp_if_ssh is True:
  957. methods = ['scp']
  958. else:
  959. methods = ['sftp']
  960. for method in methods:
  961. returncode = stdout = stderr = None
  962. if method == 'sftp':
  963. cmd = self._build_command(self.get_option('sftp_executable'), to_bytes(host))
  964. in_data = u"{0} {1} {2}\n".format(sftp_action, shlex_quote(in_path), shlex_quote(out_path))
  965. in_data = to_bytes(in_data, nonstring='passthru')
  966. (returncode, stdout, stderr) = self._bare_run(cmd, in_data, checkrc=False)
  967. elif method == 'scp':
  968. scp = self.get_option('scp_executable')
  969. if sftp_action == 'get':
  970. cmd = self._build_command(scp, u'{0}:{1}'.format(host, self._shell.quote(in_path)), out_path)
  971. else:
  972. cmd = self._build_command(scp, in_path, u'{0}:{1}'.format(host, self._shell.quote(out_path)))
  973. in_data = None
  974. (returncode, stdout, stderr) = self._bare_run(cmd, in_data, checkrc=False)
  975. elif method == 'piped':
  976. if sftp_action == 'get':
  977. # we pass sudoable=False to disable pty allocation, which
  978. # would end up mixing stdout/stderr and screwing with newlines
  979. (returncode, stdout, stderr) = self.exec_command('dd if=%s bs=%s' % (in_path, BUFSIZE), sudoable=False)
  980. with open(to_bytes(out_path, errors='surrogate_or_strict'), 'wb+') as out_file:
  981. out_file.write(stdout)
  982. else:
  983. with open(to_bytes(in_path, errors='surrogate_or_strict'), 'rb') as f:
  984. in_data = to_bytes(f.read(), nonstring='passthru')
  985. if not in_data:
  986. count = ' count=0'
  987. else:
  988. count = ''
  989. (returncode, stdout, stderr) = self.exec_command('dd of=%s bs=%s%s' % (out_path, BUFSIZE, count), in_data=in_data, sudoable=False)
  990. # Check the return code and rollover to next method if failed
  991. if returncode == 0:
  992. return (returncode, stdout, stderr)
  993. else:
  994. # If not in smart mode, the data will be printed by the raise below
  995. if len(methods) > 1:
  996. display.warning(u'%s transfer mechanism failed on %s. Use ANSIBLE_DEBUG=1 to see detailed information' % (method, host))
  997. display.debug(u'%s' % to_text(stdout))
  998. display.debug(u'%s' % to_text(stderr))
  999. if returncode == 255:
  1000. raise AnsibleConnectionFailure("Failed to connect to the host via %s: %s" % (method, to_native(stderr)))
  1001. else:
  1002. raise AnsibleError("failed to transfer file to %s %s:\n%s\n%s" %
  1003. (to_native(in_path), to_native(out_path), to_native(stdout), to_native(stderr)))
  1004. def _escape_win_path(self, path):
  1005. """ converts a Windows path to one that's supported by SFTP and SCP """
  1006. # If using a root path then we need to start with /
  1007. prefix = ""
  1008. if re.match(r'^\w{1}:', path):
  1009. prefix = "/"
  1010. # Convert all '\' to '/'
  1011. return "%s%s" % (prefix, path.replace("\\", "/"))
  1012. #
  1013. # Main public methods
  1014. #
  1015. def exec_command(self, cmd, in_data=None, sudoable=False):
  1016. ''' run a command on the remote host '''
  1017. super(Connection, self).exec_command(cmd, in_data=in_data, sudoable=sudoable)
  1018. display.vvv(
  1019. "ESTABLISH SSH_LXC CONNECTION TO {1}, AS SSH USER: {0}".format(self._play_context.remote_user,
  1020. self.container_name),
  1021. host=self._play_context.remote_addr
  1022. )
  1023. if getattr(self._shell, "_IS_WINDOWS", False):
  1024. # Become method 'runas' is done in the wrapper that is executed,
  1025. # need to disable sudoable so the bare_run is not waiting for a
  1026. # prompt that will not occur
  1027. sudoable = False
  1028. # Make sure our first command is to set the console encoding to
  1029. # utf-8, this must be done via chcp to get utf-8 (65001)
  1030. cmd_parts = ["chcp.com", "65001", self._shell._SHELL_REDIRECT_ALLNULL, self._shell._SHELL_AND]
  1031. cmd_parts.extend(self._shell._encode_script(cmd, as_list=True, strict_mode=False, preserve_rc=False))
  1032. cmd = ' '.join(cmd_parts)
  1033. # we can only use tty when we are not pipelining the modules. piping
  1034. # data into /usr/bin/python inside a tty automatically invokes the
  1035. # python interactive-mode but the modules are not compatible with the
  1036. # interactive-mode ("unexpected indent" mainly because of empty lines)
  1037. ssh_executable = self._play_context.ssh_executable
  1038. lxc_cmd = 'lxc-attach --name %s -- /bin/sh -c %s' % (shlex_quote(self.container_name),
  1039. shlex_quote(cmd))
  1040. # -tt can cause various issues in some environments so allow the user
  1041. # to disable it as a troubleshooting method.
  1042. use_tty = self.get_option('use_tty')
  1043. if not in_data and sudoable and use_tty:
  1044. args = (ssh_executable, '-tt', self.host, lxc_cmd)
  1045. else:
  1046. args = (ssh_executable, self.host, lxc_cmd)
  1047. cmd = self._build_command(*args)
  1048. (returncode, stdout, stderr) = self._run(cmd, in_data, sudoable=sudoable)
  1049. # When running on Windows, stderr may contain CLIXML encoded output
  1050. if getattr(self._shell, "_IS_WINDOWS", False) and stderr.startswith(b"#< CLIXML"):
  1051. stderr = _parse_clixml(stderr)
  1052. return (returncode, stdout, stderr)
  1053. def put_file(self, in_path, out_path):
  1054. ''' transfer a file from local to remote '''
  1055. super(Connection, self).put_file(in_path, out_path)
  1056. display.vvv(u"PUT {0} TO {1}".format(in_path, out_path), host=self.host)
  1057. if not os.path.exists(to_bytes(in_path, errors='surrogate_or_strict')):
  1058. raise AnsibleFileNotFound("file or module does not exist: {0}".format(to_native(in_path)))
  1059. if getattr(self._shell, "_IS_WINDOWS", False):
  1060. out_path = self._escape_win_path(out_path)
  1061. with open(in_path, 'rb') as in_f:
  1062. in_data = in_f.read()
  1063. cmd = 'cat > %s; echo -n done' % shlex_quote(out_path)
  1064. return self.exec_command(cmd, in_data, sudoable=False)
  1065. def fetch_file(self, in_path, out_path):
  1066. ''' fetch a file from remote to local '''
  1067. super(Connection, self).fetch_file(in_path, out_path)
  1068. display.vvv(u"FETCH {0} TO {1}".format(in_path, out_path), host=self.host)
  1069. # need to add / if path is rooted
  1070. if getattr(self._shell, "_IS_WINDOWS", False):
  1071. in_path = self._escape_win_path(in_path)
  1072. cmd = 'cat %s' % shlex_quote(in_path)
  1073. (returncode, stdout, stderr) = self.exec_command(cmd, in_data=None, sudoable=False)
  1074. if returncode != 0:
  1075. raise AnsibleError("failed to transfer file from {0}:\n{1}\n{2}".format(in_path, stdout, stderr))
  1076. with open(out_path,'wb') as out_f:
  1077. out_f.write(stdout)
  1078. def reset(self):
  1079. # If we have a persistent ssh connection (ControlPersist), we can ask it to stop listening.
  1080. cmd = self._build_command(self._play_context.ssh_executable, '-O', 'stop', self.host)
  1081. controlpersist, controlpath = self._persistence_controls(cmd)
  1082. cp_arg = [a for a in cmd if a.startswith(b"ControlPath=")]
  1083. # only run the reset if the ControlPath already exists or if it isn't
  1084. # configured and ControlPersist is set
  1085. run_reset = False
  1086. if controlpersist and len(cp_arg) > 0:
  1087. cp_path = cp_arg[0].split(b"=", 1)[-1]
  1088. if os.path.exists(cp_path):
  1089. run_reset = True
  1090. elif controlpersist:
  1091. run_reset = True
  1092. if run_reset:
  1093. display.vvv(u'sending stop: %s' % to_text(cmd))
  1094. p = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  1095. stdout, stderr = p.communicate()
  1096. status_code = p.wait()
  1097. if status_code != 0:
  1098. display.warning(u"Failed to reset connection:%s" % to_text(stderr))
  1099. self.close()
  1100. def close(self):
  1101. self._connected = False