forked from chifflier/ansible-lxc-ssh
-
Notifications
You must be signed in to change notification settings - Fork 23
/
lxc_ssh.py
1546 lines (1394 loc) · 58.1 KB
/
lxc_ssh.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright 2016 Pierre Chifflier <pollux@wzdftpd.net>
# SPDX-License-Identifier: GPL-3.0-or-later
#
# SSH + lxc-attach connection module for Ansible 2.0
#
# Adapted from ansible/plugins/connection/ssh.py
# Forked from https://github.com/chifflier/ansible-lxc-ssh
# Hosted on https://github.com/andreasscherbaum/ansible-lxc-ssh
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
from __future__ import absolute_import, division, print_function
__metaclass__ = type
import errno
import fcntl
import hashlib
import os
import pipes
import pty
import shlex
import subprocess
import sys
import time
from ansible.release import __version__ as ansible_version
from functools import wraps
from ansible import constants as C
from ansible.errors import (
AnsibleError,
AnsibleConnectionFailure,
AnsibleFileNotFound,
)
from ansible.errors import AnsibleOptionsError
from ansible.compat import selectors
from ansible.module_utils.six import PY3, text_type, binary_type
from ansible.module_utils.six.moves import shlex_quote
from ansible.module_utils._text import to_bytes, to_native, to_text
from ansible.module_utils.parsing.convert_bool import BOOLEANS, boolean
from ansible.plugins.connection import ConnectionBase, BUFSIZE
from ansible.utils.path import unfrackpath, makedirs_safe
from ansible.module_utils._text import (
to_bytes,
to_text as to_unicode,
to_native as to_str,
)
DOCUMENTATION = """
name: lxc_ssh
short_description: connect via ssh and lxc to remote lxc guest
description:
- This connection plugin allows ansible to communicate to the target
machines via normal ssh and lxc cli.
- Ansible does not expose a channel to allow communication between the
user and the ssh process to accept a password manually to decrypt an
ssh key when using this connection plugin (which is the default). The
use of ``ssh-agent`` is highly recommended.
author: Pierre Chifflier
notes:
- Many options default to 'None' here but that only means we don't
override the ssh tool's defaults and/or configuration.
For example, if you specify the port in this plugin it will override
any C(Port) entry in your C(.ssh/config).
options:
host:
description: Hostname/ip to connect to.
vars:
- name: inventory_hostname
- name: ansible_host
- name: ansible_ssh_host
- name: delegated_vars['ansible_host']
- name: delegated_vars['ansible_ssh_host']
host_key_checking:
description: Determines if ssh should check host keys
type: boolean
ini:
- section: defaults
key: 'host_key_checking'
- section: ssh_connection
key: 'host_key_checking'
version_added: '2.5'
env:
- name: ANSIBLE_HOST_KEY_CHECKING
- name: ANSIBLE_SSH_HOST_KEY_CHECKING
version_added: '2.5'
vars:
- name: ansible_host_key_checking
version_added: '2.5'
- name: ansible_ssh_host_key_checking
version_added: '2.5'
password:
description: Authentication password for the C(remote_user).
Can be supplied as CLI option.
vars:
- name: ansible_password
- name: ansible_ssh_pass
- name: ansible_ssh_password
sshpass_prompt:
description: Password prompt that sshpass should search for.
Supported by sshpass 1.06 and up.
default: ''
ini:
- section: 'ssh_connection'
key: 'sshpass_prompt'
env:
- name: ANSIBLE_SSHPASS_PROMPT
vars:
- name: ansible_sshpass_prompt
version_added: '2.10'
ssh_args:
description: Arguments to pass to all ssh cli tools
default: '-C -o ControlMaster=auto -o ControlPersist=60s'
ini:
- section: 'ssh_connection'
key: 'ssh_args'
env:
- name: ANSIBLE_SSH_ARGS
vars:
- name: ansible_ssh_args
version_added: '2.7'
cli:
- name: ssh_args
ssh_common_args:
description: Common extra args for all ssh CLI tools
ini:
- section: 'ssh_connection'
key: 'ssh_common_args'
version_added: '2.7'
env:
- name: ANSIBLE_SSH_COMMON_ARGS
version_added: '2.7'
vars:
- name: ansible_ssh_common_args
cli:
- name: ssh_common_args
ssh_executable:
default: ssh
description:
- This defines the location of the ssh binary.
It defaults to ``ssh`` which will use the first ssh binary
available in $PATH.
- This option is usually not required, it might be useful when
access to system ssh is restricted,
or when using ssh wrappers to connect to remote hosts.
env: [{name: ANSIBLE_SSH_EXECUTABLE}]
ini:
- {key: ssh_executable, section: ssh_connection}
#const: ANSIBLE_SSH_EXECUTABLE
version_added: "2.2"
vars:
- name: ansible_ssh_executable
version_added: '2.7'
sftp_executable:
default: sftp
description:
- This defines the location of the sftp binary. It defaults to
``sftp`` which will use the first binary available in $PATH.
env: [{name: ANSIBLE_SFTP_EXECUTABLE}]
ini:
- {key: sftp_executable, section: ssh_connection}
version_added: "2.6"
vars:
- name: ansible_sftp_executable
version_added: '2.7'
scp_executable:
default: scp
description:
- This defines the location of the scp binary. It defaults to
`scp` which will use the first binary available in $PATH.
env: [{name: ANSIBLE_SCP_EXECUTABLE}]
ini:
- {key: scp_executable, section: ssh_connection}
version_added: "2.6"
vars:
- name: ansible_scp_executable
version_added: '2.7'
scp_extra_args:
description: Extra exclusive to the ``scp`` CLI
vars:
- name: ansible_scp_extra_args
env:
- name: ANSIBLE_SCP_EXTRA_ARGS
version_added: '2.7'
ini:
- key: scp_extra_args
section: ssh_connection
version_added: '2.7'
cli:
- name: scp_extra_args
sftp_extra_args:
description: Extra exclusive to the ``sftp`` CLI
vars:
- name: ansible_sftp_extra_args
env:
- name: ANSIBLE_SFTP_EXTRA_ARGS
version_added: '2.7'
ini:
- key: sftp_extra_args
section: ssh_connection
version_added: '2.7'
cli:
- name: sftp_extra_args
ssh_extra_args:
description: Extra exclusive to the 'ssh' CLI
vars:
- name: ansible_ssh_extra_args
env:
- name: ANSIBLE_SSH_EXTRA_ARGS
version_added: '2.7'
ini:
- key: ssh_extra_args
section: ssh_connection
version_added: '2.7'
cli:
- name: ssh_extra_args
retries:
description: Number of attempts to connect.
default: 3
type: integer
env:
- name: ANSIBLE_SSH_RETRIES
ini:
- section: connection
key: retries
- section: ssh_connection
key: retries
vars:
- name: ansible_ssh_retries
version_added: '2.7'
port:
description: Remote port to connect to.
type: int
ini:
- section: defaults
key: remote_port
env:
- name: ANSIBLE_REMOTE_PORT
vars:
- name: ansible_port
- name: ansible_ssh_port
remote_user:
description:
- User name with which to login to the remote server, normally
set by the remote_user keyword.
- If no user is supplied, Ansible will let the ssh client binary
choose the user as it normally
ini:
- section: defaults
key: remote_user
env:
- name: ANSIBLE_REMOTE_USER
vars:
- name: ansible_user
- name: ansible_ssh_user
cli:
- name: user
pipelining:
description: Enable ssh pipelining.
env:
- name: ANSIBLE_PIPELINING
- name: ANSIBLE_SSH_PIPELINING
ini:
- section: connection
key: pipelining
- section: ssh_connection
key: pipelining
vars:
- name: ansible_pipelining
- name: ansible_ssh_pipelining
private_key_file:
description:
- Path to private key file to use for authentication
ini:
- section: defaults
key: private_key_file
env:
- name: ANSIBLE_PRIVATE_KEY_FILE
vars:
- name: ansible_private_key_file
- name: ansible_ssh_private_key_file
cli:
- name: private_key_file
control_path:
description:
- This is the location to save ssh's ControlPath sockets, it uses
ssh's variable substitution.
- Since 2.3, if null (default), ansible will generate a unique hash.
Use `%(directory)s` to indicate where to use the control dir path
setting.
- Before 2.3 it defaulted to
`control_path=%(directory)s/ansible-ssh-%%h-%%p-%%r`.
- Be aware that this setting is ignored if `-o ControlPath` is set
in ssh args.
env:
- name: ANSIBLE_SSH_CONTROL_PATH
ini:
- key: control_path
section: ssh_connection
vars:
- name: ansible_control_path
version_added: '2.7'
control_path_dir:
default: ~/.ansible/cp
description:
- This sets the directory to use for ssh control path if the control
path setting is null.
- Also, provides the `%(directory)s` variable for the control
path setting.
env:
- name: ANSIBLE_SSH_CONTROL_PATH_DIR
ini:
- section: ssh_connection
key: control_path_dir
vars:
- name: ansible_control_path_dir
version_added: '2.7'
sftp_batch_mode:
default: 'yes'
description: 'TODO: write it'
env: [{name: ANSIBLE_SFTP_BATCH_MODE}]
ini:
- {key: sftp_batch_mode, section: ssh_connection}
type: bool
vars:
- name: ansible_sftp_batch_mode
version_added: '2.7'
ssh_transfer_method:
default: smart
description:
- "Preferred method to use when transferring files over ssh"
- Setting to 'smart' (default) will try them in order, until one
succeeds or they all fail
- Using 'piped' creates an ssh pipe with ``dd`` on either side to
copy the data
choices: ['sftp', 'scp', 'piped', 'smart']
env: [{name: ANSIBLE_SSH_TRANSFER_METHOD}]
ini:
- {key: transfer_method, section: ssh_connection}
scp_if_ssh:
default: smart
description:
- "Preferred method to use when transfering files over ssh"
- When set to smart, Ansible will try them until one succeeds or they
all fail
- If set to True, it will force 'scp', if False it will use 'sftp'
env: [{name: ANSIBLE_SCP_IF_SSH}]
ini:
- {key: scp_if_ssh, section: ssh_connection}
vars:
- name: ansible_scp_if_ssh
version_added: '2.7'
use_tty:
version_added: '2.5'
default: 'yes'
description: add -tt to ssh commands to force tty allocation
env: [{name: ANSIBLE_SSH_USETTY}]
ini:
- {key: usetty, section: ssh_connection}
type: bool
vars:
- name: ansible_ssh_use_tty
version_added: '2.7'
timeout:
default: 10
description:
- This is the default ammount of time we will wait while
establishing an ssh connection
- It also controls how long we can wait to access reading the
connection once established (select on the socket)
env:
- name: ANSIBLE_TIMEOUT
- name: ANSIBLE_SSH_TIMEOUT
version_added: '2.11'
ini:
- key: timeout
section: defaults
- key: timeout
section: ssh_connection
version_added: '2.11'
vars:
- name: ansible_ssh_timeout
version_added: '2.11'
cli:
- name: timeout
type: integer
lxc_host:
description:
The lxc host to connect to.
env:
- name: LXC_HOST
- name: LXC_CONTAINER
ini:
- key: lxc_host
section: lxc_ssh_connection
- key: lxc_container
section: lxc_ssh_connection
vars:
- name: lxc_host
- name: lxc_container
cli:
- name: lxc_host
- name: lxc_container
"""
try:
from __main__ import display
except ImportError:
from ansible.utils.display import Display
display = Display()
class AnsibleControlPersistBrokenPipeError(AnsibleError):
"""ControlPersist broken pipe"""
pass
def _ssh_retry(func):
"""
Decorator to retry ssh/scp/sftp in the case of a connection failure
Will retry if:
* an exception is caught
* ssh returns 255
Will not retry if
* remaining_tries is <2
* retries limit reached
"""
@wraps(func)
def wrapped(self, *args, **kwargs):
remaining_tries = int(self.get_option("retries")) + 1
cmd_summary = "%s..." % args[0]
for attempt in range(remaining_tries):
cmd = args[0]
if attempt != 0 and self._play_context.password and isinstance(cmd, list):
# If this is a retry, the fd/pipe for sshpass is closed,
# and we need a new one
self.sshpass_pipe = os.pipe()
cmd[1] = b"-d" + to_bytes(
self.sshpass_pipe[0],
nonstring="simplerepr",
errors="surrogate_or_strict",
)
try:
try:
return_tuple = func(self, *args, **kwargs)
display.vvv(return_tuple, host=self.host)
# 0 = success
# 1-254 = remote command return code
# 255 = failure from the ssh command itself
except (AnsibleControlPersistBrokenPipeError) as e:
# Retry one more time because of the ControlPersist
# broken pipe (see #16731)
display.vvv("RETRYING BECAUSE OF CONTROLPERSIST BROKEN PIPE")
return_tuple = func(self, *args, **kwargs)
if return_tuple[0] != 255:
break
else:
raise AnsibleConnectionFailure(
"Failed to connect to the host via ssh: %s"
% to_native(return_tuple[2])
)
except (AnsibleConnectionFailure, Exception) as e:
if attempt == remaining_tries - 1:
raise
else:
pause = 2**attempt - 1
if pause > 30:
pause = 30
if isinstance(e, AnsibleConnectionFailure):
msg = (
"ssh_retry: attempt: %d, ssh return code is 255. "
"cmd (%s), pausing for %d seconds"
% (attempt, cmd_summary, pause)
)
else:
msg = (
"ssh_retry: attempt: %d, caught exception(%s) "
"from cmd (%s), pausing for %d seconds"
% (attempt, e, cmd_summary, pause)
)
display.vv(msg, host=self.host)
time.sleep(pause)
continue
return return_tuple
return wrapped
SSHPASS_AVAILABLE = None
class Connection(ConnectionBase):
"""ssh+lxc_attach connection"""
transport = "lxc_ssh"
def __init__(self, play_context, new_stdin, *args, **kwargs):
super(Connection, self).__init__(play_context, new_stdin, *args, **kwargs)
self.host = self._play_context.remote_addr
self.port = self._play_context.port
self.user = self._play_context.remote_user
self.control_path = None
self.control_path_dir = None
def _set_command_prefix(self):
# check for cgroupv2 and use systemd-run to run the commands if needed
(returncode_cgroup, stdout_cgroup, stderr_cgroup) = self._exec_command(
"stat /sys/fs/cgroup/cgroup.controllers", None, False
)
cgroup2 = returncode_cgroup == 0
if cgroup2:
self.systemd_run_prefix = (
'systemd-run --quiet --user --scope --property="Delegate=yes" -- '
)
else:
self.systemd_run_prefix = ""
def _set_version(self):
# LXC v1 uses 'lxc-info', 'lxc-attach' and so on
# LXC v2 uses just 'lxc'
(returncode2, stdout2, stderr2) = self._exec_command("which lxc", None, False)
(returncode1, stdout1, stderr1) = self._exec_command(
"which lxc-info", None, False
)
if returncode2 == 0:
self.lxc_version = 2
display.vvv("LXC v2")
elif returncode1 == 0:
self.lxc_version = 1
display.vvv("LXC v1")
else:
raise AnsibleConnectionFailure("Cannot identify LXC version")
sys.exit(1)
def set_options(self, *args, **kwargs):
super(Connection, self).set_options(*args, **kwargs)
self._set_version()
self._set_command_prefix()
# The connection is created by running ssh/scp/sftp from the exec_command,
# put_file, and fetch_file methods, so we don't need to do any connection
# management here.
def _connect(self):
"""connect to the lxc; nothing to do here"""
display.vvv("XXX connect")
super(Connection, self)._connect()
self.container_name = str(self.get_option("lxc_host"))
@staticmethod
def _sshpass_available():
global SSHPASS_AVAILABLE
# We test once if sshpass is available, and remember the result. It
# would be nice to use distutils.spawn.find_executable for this, but
# distutils isn't always available; shutils.which() is Python3-only.
if SSHPASS_AVAILABLE is None:
try:
p = subprocess.Popen(
["sshpass"],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
p.communicate()
SSHPASS_AVAILABLE = True
except OSError:
SSHPASS_AVAILABLE = False
return SSHPASS_AVAILABLE
@staticmethod
def _create_control_path(host, port, user, connection=None):
"""Make a hash for the controlpath based on con attributes"""
pstring = "%s-%s-%s" % (host, port, user)
if connection:
pstring += "-%s" % connection
m = hashlib.sha1()
m.update(to_bytes(pstring))
digest = m.hexdigest()
cpath = "%(directory)s/" + digest[:10]
return cpath
@staticmethod
def _persistence_controls(b_command):
"""
Takes a command array and scans it for ControlPersist and ControlPath
settings and returns two booleans indicating whether either was found.
This could be smarter, e.g. returning false if ControlPersist is 'no',
but for now we do it simple way.
"""
controlpersist = False
controlpath = False
for b_arg in (a.lower() for a in b_command):
if b"controlpersist" in b_arg:
controlpersist = True
elif b"controlpath" in b_arg:
controlpath = True
return controlpersist, controlpath
@staticmethod
def _split_args(argstring):
"""
Takes a string like '-o Foo=1 -o Bar="foo bar"' and returns a
list ['-o', 'Foo=1', '-o', 'Bar=foo bar'] that can be added to
the argument list. The list will not contain any empty elements.
"""
if sys.version_info[0] >= 3:
return [
to_unicode(x.strip())
for x in shlex.split(to_bytes(argstring).decode())
if x.strip()
]
else:
return [
to_unicode(x.strip())
for x in shlex.split(to_bytes(argstring))
if x.strip()
]
def _add_args(self, b_command, b_args, explanation):
"""
Adds arguments to the ssh command and displays a caller-supplied
explanation of why.
:arg b_command: A list containing the command to add the new arguments
to. This list will be modified by this method.
:arg b_args: An iterable of new arguments to add. This iterable is
used more than once so it must be persistent (ie: a list is okay
but a StringIO would not)
:arg explanation: A text string containing explaining why the arguments
were added. It will be displayed with a high enough verbosity.
.. note:: This function does its work via side-effect.
The b_command list has the new arguments appended.
"""
display.vvvvv(
"SSH: %s: (%s)" % (explanation, ")(".join(to_text(a) for a in b_args)),
host=self._play_context.remote_addr,
)
b_command += b_args
def _build_command(self, binary, subsystem, *other_args):
"""
Takes an executable (ssh, scp, sftp or wrapper) and optional extra
arguments and returns the remote command wrapped in local ssh shell
commands and ready for execution.
:arg binary: actual executable to use to execute command.
:arg subsystem: type of executable provided, ssh/sftp/scp,
needed because wrappers for ssh might have diff names.
:arg other_args: dict of, value pairs passed as arguments to the ssh
binary
"""
b_command = []
conn_password = self.get_option("password") or self._play_context.password
#
# First, the command to invoke
#
# If we want to use password authentication, we have to set up a pipe to
# write the password to sshpass.
if conn_password:
if not self._sshpass_available():
raise AnsibleError(
"to use the 'ssh' connection type with passwords, "
" you must install the sshpass program"
)
self.sshpass_pipe = os.pipe()
b_command += [
b"sshpass",
b"-d"
+ to_bytes(
self.sshpass_pipe[0],
nonstring="simplerepr",
errors="surrogate_or_strict",
),
]
password_prompt = self.get_option("sshpass_prompt")
if password_prompt:
b_command += [
b"-P",
to_bytes(password_prompt, errors="surrogate_or_strict"),
]
b_command += [to_bytes(binary, errors="surrogate_or_strict")]
#
# Next, additional arguments based on the configuration.
#
# sftp batch mode allows us to correctly catch failed transfers, but can
# be disabled if the client side doesn't support the option. However,
# sftp batch mode does not prompt for passwords so it must be disabled
# if not using controlpersist and using sshpass
if subsystem == "sftp" and self.get_option("sftp_batch_mode"):
if conn_password:
b_args = [b"-o", b"BatchMode=no"]
self._add_args(b_command, b_args, "disable batch mode for sshpass")
b_command += [b"-b", b"-"]
if self._display.verbosity == 1:
b_command.append(b"-v")
elif self._display.verbosity == 2:
b_command.append(b"-vv")
elif self._display.verbosity >= 3:
b_command.append(b"-vvv")
# Next, we add ssh_args
ssh_args = self.get_option("ssh_args")
if ssh_args:
b_args = [
to_bytes(a, errors="surrogate_or_strict")
for a in self._split_ssh_args(ssh_args)
]
self._add_args(b_command, b_args, "ansible.cfg set ssh_args")
# Now we add various arguments that have their own specific settings
# defined in docs above.
if not self.get_option("host_key_checking"):
b_args = (b"-o", b"StrictHostKeyChecking=no")
self._add_args(
b_command,
b_args,
"ANSIBLE_HOST_KEY_CHECKING/host_key_checking disabled",
)
self.port = self.get_option("port")
if self.port is not None:
b_args = (
b"-o",
b"Port="
+ to_bytes(
self.port,
nonstring="simplerepr",
errors="surrogate_or_strict",
),
)
self._add_args(
b_command,
b_args,
"ANSIBLE_REMOTE_PORT/remote_port/ansible_port set",
)
key = self.get_option("private_key_file")
if key:
b_args = (
b"-o",
b'IdentityFile="'
+ to_bytes(os.path.expanduser(key), errors="surrogate_or_strict")
+ b'"',
)
self._add_args(
b_command,
b_args,
"ANSIBLE_PRIVATE_KEY_FILE/private_key_file/"
"ansible_ssh_private_key_file set",
)
if not conn_password:
self._add_args(
b_command,
(
b"-o",
b"KbdInteractiveAuthentication=no",
b"-o",
b"PreferredAuthentications=publickey,gssapi-with-mic,"
b"gssapi-keyex,hostbased",
b"-o",
b"PasswordAuthentication=no",
),
"ansible_password/ansible_ssh_password not set",
)
self.user = self.get_option("remote_user")
if self.user:
self._add_args(
b_command,
(
b"-o",
b'User="%s"' % to_bytes(self.user, errors="surrogate_or_strict"),
),
"ANSIBLE_REMOTE_USER/remote_user/ansible_user/user/-u set",
)
timeout = self.get_option("timeout")
self._add_args(
b_command,
(
b"-o",
b"ConnectTimeout="
+ to_bytes(
timeout,
errors="surrogate_or_strict",
nonstring="simplerepr",
),
),
"ANSIBLE_TIMEOUT/timeout set",
)
# Add in any common or binary-specific arguments from the PlayContext
# (i.e. inventory or task settings or overrides on the command line).
for opt in ("ssh_common_args", "{0}_extra_args".format(subsystem)):
attr = self.get_option(opt)
if attr is not None:
b_args = [
to_bytes(a, errors="surrogate_or_strict")
for a in self._split_ssh_args(attr)
]
self._add_args(b_command, b_args, "Set %s" % opt)
# Check if ControlPersist is enabled and add a ControlPath if one hasn't
# already been set.
controlpersist, controlpath = self._persistence_controls(b_command)
if controlpersist:
self._persistent = True
if not controlpath:
self.control_path_dir = self.get_option("control_path_dir")
cpdir = unfrackpath(self.control_path_dir)
b_cpdir = to_bytes(cpdir, errors="surrogate_or_strict")
# The directory must exist and be writable.
makedirs_safe(b_cpdir, 0o700)
if not os.access(b_cpdir, os.W_OK):
raise AnsibleError(
"Cannot write to ControlPath %s" % to_native(cpdir)
)
self.control_path = self.get_option("control_path")
if not self.control_path:
self.control_path = self._create_control_path(
self.host, self.port, self.user
)
b_args = (
b"-o",
b"ControlPath="
+ to_bytes(
self.control_path % dict(directory=cpdir),
errors="surrogate_or_strict",
),
)
self._add_args(
b_command,
b_args,
"found only ControlPersist; added ControlPath",
)
# Finally, we add any caller-supplied extras.
if other_args:
b_command += [to_bytes(a) for a in other_args]
return b_command
def _send_initial_data(self, fh, in_data):
"""
Writes initial data to the stdin filehandle of the subprocess and closes
it. (The handle must be closed; otherwise, for example, "sftp -b -" will
just hang forever waiting for more commands.)
"""
display.debug("Sending initial data")
try:
fh.write(to_bytes(in_data))
fh.close()
except (OSError, IOError):
raise AnsibleConnectionFailure(
'SSH Error: data could not be sent to remote host "%s". '
"Make sure this host can be reached over ssh" % self.host
)
display.debug("Sent initial data (%d bytes)" % len(in_data))
# Used by _run() to kill processes on failures
@staticmethod
def _terminate_process(p):
"""Terminate a process, ignoring errors"""
try:
p.terminate()
except (OSError, IOError):
pass
# This is separate from _run() because we need to do the same
# thing for stdout and stderr.
def _examine_output(self, source, state, b_chunk, sudoable):
"""
Takes a string, extracts complete lines from it, tests to see if they
are a prompt, error message, etc., and sets appropriate flags in self.
Prompt and success lines are removed.
Returns the processed (i.e. possibly-edited) output and the unprocessed
remainder (to be processed with the next chunk) as strings.
"""
output = []
for b_line in b_chunk.splitlines(True):
display_line = to_text(b_line).rstrip("\r\n")
suppress_output = False
if self._play_context.prompt and self.check_password_prompt(b_line):
display.debug(
"become_prompt: (source=%s, state=%s): '%s'"
% (source, state, display_line)
)
self._flags["become_prompt"] = True
suppress_output = True
elif self._play_context.success_key and self.check_become_success(b_line):
display.debug(
"become_success: (source=%s, state=%s): '%s'"
% (source, state, display_line)
)
self._flags["become_success"] = True
suppress_output = True
elif sudoable and self.check_incorrect_password(b_line):
display.debug(
"become_error: (source=%s, state=%s): '%s'"
% (source, state, display_line)
)
self._flags["become_error"] = True
elif sudoable and self.check_missing_password(b_line):
display.debug(
"become_nopasswd_error: (source=%s, state=%s): '%s'"
% (source, state, display_line)
)
self._flags["become_nopasswd_error"] = True
if not suppress_output:
output.append(b_line)
# The chunk we read was most likely a series of complete lines, but just
# in case the last line was incomplete (and not a prompt, which we would
# have removed from the output), we retain it to be processed with the
# next chunk.
remainder = b""
if output and not output[-1].endswith(b"\n"):
remainder = output[-1]
output = output[:-1]
return b"".join(output), remainder
def _bare_run(self, cmd, in_data, sudoable=True, checkrc=True):
"""
Starts the command and communicates with it until it ends.
"""
display_cmd = list(map(shlex_quote, map(to_text, cmd)))
display.vvv("SSH: EXEC {0}".format(" ".join(display_cmd)), host=self.host)
# Start the given command. If we don't need to pipeline data, we can try
# to use a pseudo-tty (ssh will have been invoked with -tt). If we are
# pipelining data, or can't create a pty, we fall back to using plain
# old pipes.
p = None
if isinstance(cmd, (text_type, binary_type)):
cmd = to_bytes(cmd)
else:
if sys.version_info[0] >= 3:
cmd = list(map(to_bytes, cmd))
else:
cmd = map(to_bytes, cmd)
if not in_data:
try:
# Make sure stdin is a proper pty to avoid tcgetattr errors