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.

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