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.

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