This repository was archived by the owner on Jan 15, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 77
Expand file tree
/
Copy pathssh.py
More file actions
1697 lines (1469 loc) · 66 KB
/
ssh.py
File metadata and controls
1697 lines (1469 loc) · 66 KB
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 2014-2024 ARM Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import os
import stat
import logging
from pathlib import Path
import subprocess
import re
import threading
import tempfile
import socket
import sys
import time
import contextlib
import select
import copy
import functools
import shutil
from shlex import quote
from paramiko.client import SSHClient, AutoAddPolicy, RejectPolicy
import paramiko.ssh_exception
from scp import SCPClient
# By default paramiko is very verbose, including at the INFO level
logging.getLogger("paramiko").setLevel(logging.WARNING)
# pylint: disable=import-error,wrong-import-position,ungrouped-imports,wrong-import-order
import pexpect
try:
from pexpect import pxssh
# pexpect < 4.0.0 does not have a pxssh module
except ImportError:
import pxssh
from pexpect import EOF, TIMEOUT, spawn
# pylint: disable=redefined-builtin,wrong-import-position
from devlib.exception import (HostError, TargetStableError, TargetNotRespondingError,
TimeoutError, TargetTransientError,
TargetCalledProcessError,
TargetTransientCalledProcessError,
TargetStableCalledProcessError)
from devlib.utils.misc import (which, strip_bash_colors, check_output,
sanitize_cmd_template, memoized, redirect_streams)
from devlib.utils.types import boolean
from devlib.connection import ConnectionBase, ParamikoBackgroundCommand, SSHTransferHandle
# Empty prompt with -p '' to avoid adding a leading space to the output.
DEFAULT_SSH_SUDO_COMMAND = "sudo -k -p '' -S -- sh -c {}"
class _SSHEnv:
@functools.lru_cache(maxsize=None)
def get_path(self, tool):
if tool in {'ssh', 'scp', 'sshpass'}:
path = which(tool)
if path:
return path
else:
raise HostError(f'OpenSSH must be installed on the host: could not find {tool} command')
else:
raise AttributeError(f"Tool '{tool}' is not supported")
_SSH_ENV = _SSHEnv()
logger = logging.getLogger('ssh')
gem5_logger = logging.getLogger('gem5-connection')
@contextlib.contextmanager
def _handle_paramiko_exceptions(command=None):
try:
yield
except paramiko.ssh_exception.NoValidConnectionsError as e:
raise TargetNotRespondingError('Connection lost: {}'.format(e))
except paramiko.ssh_exception.AuthenticationException as e:
raise TargetStableError('Could not authenticate: {}'.format(e))
except paramiko.ssh_exception.BadAuthenticationType as e:
raise TargetStableError('Bad authentication type: {}'.format(e))
except paramiko.ssh_exception.BadHostKeyException as e:
raise TargetStableError('Bad host key: {}'.format(e))
except paramiko.ssh_exception.ChannelException as e:
raise TargetStableError('Could not open an SSH channel: {}'.format(e))
except paramiko.ssh_exception.PasswordRequiredException as e:
raise TargetStableError('Please unlock the private key file: {}'.format(e))
except paramiko.ssh_exception.ProxyCommandFailure as e:
raise TargetStableError('Proxy command failure: {}'.format(e))
except paramiko.ssh_exception.SSHException as e:
raise TargetTransientError('SSH logic error: {}'.format(e))
except socket.timeout:
raise TimeoutError(command, output=None)
def _read_paramiko_streams(stdout, stderr, select_timeout, callback, init, chunk_size=int(1e42)):
try:
return _read_paramiko_streams_internal(stdout, stderr, select_timeout, callback, init, chunk_size)
finally:
# Close the channel to make sure the remove process will receive
# SIGPIPE when writing on its streams. That could happen if the
# user closed the out_streams but the remote process has not
# finished yet.
assert stdout.channel is stderr.channel
stdout.channel.close()
def _read_paramiko_streams_internal(stdout, stderr, select_timeout, callback, init, chunk_size):
channel = stdout.channel
assert stdout.channel is stderr.channel
def read_channel(callback_state):
read_list, _, _ = select.select([channel], [], [], select_timeout)
for desc in read_list:
for ready, recv, name in (
(desc.recv_ready(), desc.recv, 'stdout'),
(desc.recv_stderr_ready(), desc.recv_stderr, 'stderr')
):
if ready:
chunk = recv(chunk_size)
if chunk:
try:
callback_state = callback(callback_state, name, chunk)
except Exception as e:
return (e, callback_state)
return (None, callback_state)
def read_all_channel(callback=None, callback_state=None):
for stream, name in ((stdout, 'stdout'), (stderr, 'stderr')):
try:
chunk = stream.read()
except Exception:
continue
if callback is not None and chunk:
callback_state = callback(callback_state, name, chunk)
return callback_state
callback_excep = None
try:
callback_state = init
while not channel.exit_status_ready():
callback_excep, callback_state = read_channel(callback_state)
if callback_excep is not None:
raise callback_excep
# Make sure to always empty the streams to unblock the remote process on
# the way to exit, in case something bad happened. For example, the
# callback could raise an exception to signal it does not want to do
# anything anymore, or only reading from one of the stream might have
# raised an exception, leaving the other one non-empty.
except Exception as e:
if callback_excep is None:
# Only call the callback if there was no exception originally, as
# we don't want to reenter it if it raised an exception
read_all_channel(callback, callback_state)
raise e
else:
# Finish emptying the buffers
callback_state = read_all_channel(callback, callback_state)
exit_code = channel.recv_exit_status()
return (callback_state, exit_code)
def _resolve_known_hosts(strict_host_check):
if strict_host_check:
if isinstance(strict_host_check, (str, os.PathLike)):
path = Path(strict_host_check)
else:
path = Path('~/.ssh/known_hosts').expanduser()
else:
path = Path('/dev/null')
return str(path.resolve())
def telnet_get_shell(host,
username,
password=None,
port=None,
timeout=10,
original_prompt=None):
start_time = time.time()
while True:
conn = TelnetPxssh(original_prompt=original_prompt)
try:
conn.login(host, username, password, port=port, login_timeout=timeout)
break
except EOF:
timeout -= time.time() - start_time
if timeout <= 0:
message = 'Could not connect to {}; is the host name correct?'
raise TargetTransientError(message.format(host))
time.sleep(5)
conn.setwinsize(500, 200)
conn.sendline('')
conn.prompt()
conn.setecho(False)
return conn
class TelnetPxssh(pxssh.pxssh):
# pylint: disable=arguments-differ
def __init__(self, original_prompt):
super(TelnetPxssh, self).__init__()
self.original_prompt = original_prompt or r'[#$]'
def login(self, server, username, password='', login_timeout=10,
auto_prompt_reset=True, sync_multiplier=1, port=23):
args = ['telnet']
if username is not None:
args += ['-l', username]
args += [server, str(port)]
cmd = ' '.join(args)
spawn._spawn(self, cmd) # pylint: disable=protected-access
try:
i = self.expect('(?i)(?:password)', timeout=login_timeout)
if i == 0:
self.sendline(password)
i = self.expect([self.original_prompt, 'Login incorrect'], timeout=login_timeout)
if i:
raise pxssh.ExceptionPxssh('could not log in: password was incorrect')
except TIMEOUT:
if not password:
# No password promt before TIMEOUT & no password provided
# so assume everything is okay
pass
else:
raise pxssh.ExceptionPxssh('could not log in: did not see a password prompt')
if not self.sync_original_prompt(sync_multiplier):
self.close()
raise pxssh.ExceptionPxssh('could not synchronize with original prompt')
if auto_prompt_reset:
if not self.set_unique_prompt():
self.close()
message = 'could not set shell prompt (recieved: {}, expected: {}).'
raise pxssh.ExceptionPxssh(message.format(self.before, self.PROMPT))
return True
def check_keyfile(keyfile):
"""
keyfile must have the right access premissions in order to be useable. If the specified
file doesn't, create a temporary copy and set the right permissions for that.
Returns either the ``keyfile`` (if the permissions on it are correct) or the path to a
temporary copy with the right permissions.
"""
desired_mask = stat.S_IWUSR | stat.S_IRUSR
actual_mask = os.stat(keyfile).st_mode & 0xFF
if actual_mask != desired_mask:
tmp_file = os.path.join(tempfile.gettempdir(), os.path.basename(keyfile))
shutil.copy(keyfile, tmp_file)
os.chmod(tmp_file, desired_mask)
return tmp_file
else: # permissions on keyfile are OK
return keyfile
class SshConnectionBase(ConnectionBase):
"""
Base class for SSH connections.
"""
default_timeout = 10
@property
def name(self):
return self.host
@property
def connected_as_root(self):
if self._connected_as_root is None:
try:
result = self.execute('id', as_root=False)
except TargetStableError:
is_root = False
else:
is_root = 'uid=0(' in result
self._connected_as_root = is_root
return self._connected_as_root
@connected_as_root.setter
def connected_as_root(self, state):
self._connected_as_root = state
def __init__(self,
host,
username,
password=None,
keyfile=None,
port=None,
platform=None,
sudo_cmd=DEFAULT_SSH_SUDO_COMMAND,
strict_host_check=True,
poll_transfers=False,
start_transfer_poll_delay=30,
total_transfer_timeout=3600,
transfer_poll_period=30,
):
super().__init__(
poll_transfers=poll_transfers,
start_transfer_poll_delay=start_transfer_poll_delay,
total_transfer_timeout=total_transfer_timeout,
transfer_poll_period=transfer_poll_period,
)
self._connected_as_root = None
self.host = host
self.username = username
self.password = password
self.keyfile = check_keyfile(keyfile) if keyfile else keyfile
self.port = port
self.sudo_cmd = sanitize_cmd_template(sudo_cmd)
self.platform = platform
self.strict_host_check = strict_host_check
logger.debug('Logging in {}@{}'.format(username, host))
class SshConnection(SshConnectionBase):
# pylint: disable=unused-argument,super-init-not-called
def __init__(self,
host,
username,
password=None,
keyfile=None,
port=22,
timeout=None,
platform=None,
sudo_cmd=DEFAULT_SSH_SUDO_COMMAND,
strict_host_check=True,
use_scp=False,
poll_transfers=False,
start_transfer_poll_delay=30,
total_transfer_timeout=3600,
transfer_poll_period=30,
):
super().__init__(
host=host,
username=username,
password=password,
keyfile=keyfile,
port=port,
platform=platform,
sudo_cmd=sudo_cmd,
strict_host_check=strict_host_check,
poll_transfers=poll_transfers,
start_transfer_poll_delay=start_transfer_poll_delay,
total_transfer_timeout=total_transfer_timeout,
transfer_poll_period=transfer_poll_period,
)
self.timeout = timeout if timeout is not None else self.default_timeout
# Allow using scp for file transfer if sftp is not supported
self.use_scp = use_scp
if self.use_scp:
logger.debug('Using SCP for file transfer')
else:
logger.debug('Using SFTP for file transfer')
self.client = None
try:
self.client = self._make_client()
# Use a marker in the output so that we will be able to differentiate
# target connection issues with "password needed".
# Also, sudo might not be installed at all on the target (but
# everything will work as long as we login as root). If sudo is still
# needed, it will explode when someone tries to use it. After all, the
# user might not be interested in being root at all.
self._sudo_needs_password = (
'NEED_PASSWORD' in
self.execute(
# sudo -n is broken on some versions on MacOSX, revisit that if
# someone ever cares
'sudo -n true || echo NEED_PASSWORD',
as_root=False,
check_exit_code=False,
)
)
# pylint: disable=broad-except
except BaseException as e:
try:
if self.client is not None:
self.client.close()
finally:
raise e
def _make_client(self):
if self.strict_host_check:
policy = RejectPolicy
else:
policy = AutoAddPolicy
# Only try using SSH keys if we're not using a password
check_ssh_keys = self.password is None
with _handle_paramiko_exceptions():
client = SSHClient()
if self.strict_host_check:
client.load_system_host_keys(_resolve_known_hosts(
self.strict_host_check
))
client.set_missing_host_key_policy(policy)
get_time = time.monotonic
start = get_time()
timeout = self.timeout
while True:
try:
client.connect(
hostname=self.host,
port=self.port,
username=self.username,
password=self.password,
key_filename=self.keyfile,
timeout=timeout,
banner_timeout=timeout,
channel_timeout=timeout,
auth_timeout=timeout,
look_for_keys=check_ssh_keys,
allow_agent=check_ssh_keys
)
# There does not seem to be any *_timeout parameter that waits
# until the hostname is available, so we implement it manually
# here.
except paramiko.ssh_exception.NoValidConnectionsError as e:
elapsed = get_time() - start
timeout = self.timeout - elapsed
if timeout > 0:
sleep = min(
# Wait a good chunk of time before retrying.
self.timeout / 10,
# We still want to be able to connect ASAP, so we
# don't wait too long either until we retry. If the
# user timeout is very large, we don't want to end
# up waiting e.g. 10s before retrying.
1,
# Never sleep for longer than the remaining duration
max(
timeout / 2,
# Do not sleep less than X ms, otherwise we
# would end up splitting the remaining time
# into ever-thinner sleeps
50e-3,
)
)
time.sleep(sleep)
continue
else:
raise e
else:
break
return client
def _make_channel(self):
with _handle_paramiko_exceptions():
transport = self.client.get_transport()
channel = transport.open_session()
return channel
# Limit the number of opened channels to a low number, since some servers
# will reject more connections request. For OpenSSH, this is controlled by
# the MaxSessions config.
@functools.lru_cache(maxsize=1)
def _cached_get_sftp(self):
try:
sftp = self.client.open_sftp()
except paramiko.ssh_exception.SSHException as e:
if 'EOF during negotiation' in str(e):
raise TargetStableError('The SSH server does not support SFTP. Please install and enable appropriate module.') from e
else:
raise
return sftp
def _get_sftp(self, timeout):
sftp = self._cached_get_sftp()
sftp.get_channel().settimeout(timeout)
return sftp
@functools.lru_cache()
def _get_scp(self, timeout, callback=lambda *_: None):
cb = lambda _, to_transfer, transferred: callback(to_transfer, transferred)
return SCPClient(self.client.get_transport(), socket_timeout=timeout, progress=cb)
def _push_file(self, sftp, src, dst, callback):
sftp.put(src, dst, callback=callback)
@classmethod
def _path_exists(cls, sftp, path):
try:
sftp.lstat(path)
except FileNotFoundError:
return False
else:
return True
def _push_folder(self, sftp, src, dst, callback):
sftp.mkdir(dst)
for entry in os.scandir(src):
name = entry.name
src_path = os.path.join(src, name)
dst_path = os.path.join(dst, name)
if entry.is_dir():
push = self._push_folder
else:
push = self._push_file
push(sftp, src_path, dst_path, callback)
def _push_path(self, sftp, src, dst, callback=None):
logger.debug('Pushing via sftp: {} -> {}'.format(src, dst))
push = self._push_folder if os.path.isdir(src) else self._push_file
push(sftp, src, dst, callback)
def _pull_file(self, sftp, src, dst, callback):
try:
sftp.get(src, dst, callback=callback)
except Exception as e:
# A file may have been created by Paramiko, but we want to clean
# that up, particularly if we tried to pull a folder and failed,
# otherwise this will make subsequent attempts at pulling the
# folder fail since the destination will exist.
try:
os.remove(dst)
except Exception:
pass
raise e
def _pull_folder(self, sftp, src, dst, callback):
os.makedirs(dst)
for fileattr in sftp.listdir_attr(src):
filename = fileattr.filename
src_path = os.path.join(src, filename)
dst_path = os.path.join(dst, filename)
if stat.S_ISDIR(fileattr.st_mode):
pull = self._pull_folder
else:
pull = self._pull_file
pull(sftp, src_path, dst_path, callback)
def _pull_path(self, sftp, src, dst, callback=None):
logger.debug('Pulling via sftp: {} -> {}'.format(src, dst))
try:
self._pull_file(sftp, src, dst, callback)
except IOError:
# Maybe that was a directory, so retry as such
self._pull_folder(sftp, src, dst, callback)
def push(self, sources, dest, timeout=None):
self._push_pull('push', sources, dest, timeout)
def pull(self, sources, dest, timeout=None):
self._push_pull('pull', sources, dest, timeout)
def _push_pull(self, action, sources, dest, timeout):
if action not in ['push', 'pull']:
raise ValueError("Action must be either `push` or `pull`")
def make_handle(obj):
handle = SSHTransferHandle(obj, manager=self.transfer_manager)
cm = self.transfer_manager.manage(sources, dest, action, handle)
return (handle, cm)
# If timeout is set
if timeout is not None:
if self.use_scp:
scp = self._get_scp(timeout)
scp_cmd = getattr(scp, 'put' if action == 'push' else 'get')
scp_msg = '{}ing via scp: {} -> {}'.format(action, sources, dest)
logger.debug(scp_msg.capitalize())
scp_cmd(sources, dest, recursive=True)
else:
sftp = self._get_sftp(timeout)
sftp_cmd = getattr(self, '_' + action + '_path')
with _handle_paramiko_exceptions():
for source in sources:
sftp_cmd(sftp, source, dest)
# No timeout
elif self.use_scp:
def progress_cb(*args, **kwargs):
return handle.progress_cb(*args, **kwargs)
scp = self._get_scp(timeout, callback=progress_cb)
handle, cm = make_handle(scp)
scp_cmd = getattr(scp, 'put' if action == 'push' else 'get')
with _handle_paramiko_exceptions(), cm:
scp_msg = '{}ing via scp: {} -> {}'.format(action, sources, dest)
logger.debug(scp_msg.capitalize())
scp_cmd(sources, dest, recursive=True)
else:
sftp = self._get_sftp(timeout)
handle, cm = make_handle(sftp)
sftp_cmd = getattr(self, '_' + action + '_path')
with _handle_paramiko_exceptions(), cm:
for source in sources:
sftp_cmd(sftp, source, dest, callback=handle.progress_cb)
def execute(self, command, timeout=None, check_exit_code=True,
as_root=False, strip_colors=True, will_succeed=False): #pylint: disable=unused-argument
if command == '':
return ''
try:
with _handle_paramiko_exceptions(command):
exit_code, output = self._execute(command, timeout, as_root, strip_colors)
except TargetCalledProcessError:
raise
except TargetStableError as e:
if will_succeed:
raise TargetTransientError(e)
else:
raise
else:
if check_exit_code and exit_code:
cls = TargetTransientCalledProcessError if will_succeed else TargetStableCalledProcessError
raise cls(
exit_code,
command,
output,
None,
)
return output
def background(self, command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, as_root=False):
with _handle_paramiko_exceptions(command):
return self._background(command, stdout, stderr, as_root)
def _background(self, command, stdout, stderr, as_root):
def make_init_kwargs(command):
_stdout, _stderr, _command = redirect_streams(stdout, stderr, command)
_command = "printf '%s\n' $$; exec sh -c {}".format(quote(_command))
channel = self._make_channel()
def executor(cmd, timeout):
channel.exec_command(cmd)
# Read are not buffered so we will always get the data as soon as
# they arrive
return (
channel.makefile_stdin('w', 0),
channel.makefile(),
channel.makefile_stderr(),
)
stdin, stdout_in, stderr_in = self._execute_command(
_command,
as_root=as_root,
log=False,
timeout=None,
executor=executor,
)
pid = stdout_in.readline()
if not pid:
_stderr = stderr_in.read()
if channel.exit_status_ready():
ret = channel.recv_exit_status()
else:
ret = 126
raise subprocess.CalledProcessError(
ret,
_command,
b'',
_stderr,
)
pid = int(pid)
def create_out_stream(stream_in, stream_out):
"""
Create a pair of file-like objects. The first one is used to read
data and the second one to write.
"""
if stream_out == subprocess.DEVNULL:
r, w = None, None
# When asked for a pipe, we just give the file-like object as the
# reading end and no writing end, since paramiko already writes to
# it
elif stream_out == subprocess.PIPE:
r, w = os.pipe()
r = os.fdopen(r, 'rb')
w = os.fdopen(w, 'wb')
# Turn a file descriptor into a file-like object
elif isinstance(stream_out, int) and stream_out >= 0:
r = os.fdopen(stream_in, 'rb')
w = os.fdopen(stream_out, 'wb')
# file-like object
else:
r = stream_in
w = stream_out
return (r, w)
out_streams = {
name: create_out_stream(stream_in, stream_out)
for stream_in, stream_out, name in (
(stdout_in, _stdout, 'stdout'),
(stderr_in, _stderr, 'stderr'),
)
}
def redirect_thread_f(stdout_in, stderr_in, out_streams, select_timeout):
def callback(out_streams, name, chunk):
try:
r, w = out_streams[name]
except KeyError:
return out_streams
try:
w.write(chunk)
# Write failed
except ValueError:
# Since that stream is now closed, stop trying to write to it
del out_streams[name]
# If that was the last open stream, we raise an
# exception so the thread can terminate.
if not out_streams:
raise
return out_streams
try:
_read_paramiko_streams(stdout_in, stderr_in, select_timeout, callback, copy.copy(out_streams))
# The streams closed while we were writing to it, the job is done here
except ValueError:
pass
# Make sure the writing end are closed proper since we are not
# going to write anything anymore
for r, w in out_streams.values():
w.flush()
if r is not w and w is not None:
w.close()
# If there is anything we need to redirect to, spawn a thread taking
# care of that
select_timeout = 1
thread_out_streams = {
name: (r, w)
for name, (r, w) in out_streams.items()
if w is not None
}
redirect_thread = threading.Thread(
target=redirect_thread_f,
args=(stdout_in, stderr_in, thread_out_streams, select_timeout),
# The thread will die when the main thread dies
daemon=True,
)
redirect_thread.start()
return dict(
chan=channel,
pid=pid,
stdin=stdin,
# We give the reading end to the consumer of the data
stdout=out_streams['stdout'][0],
stderr=out_streams['stderr'][0],
redirect_thread=redirect_thread,
)
return ParamikoBackgroundCommand.from_factory(
conn=self,
cmd=command,
as_root=as_root,
make_init_kwargs=make_init_kwargs,
)
def _close(self):
logger.debug('Logging out {}@{}'.format(self.username, self.host))
with _handle_paramiko_exceptions():
self.client.close()
def _execute_command(self, command, as_root, log, timeout, executor):
# As we're already root, there is no need to use sudo.
log_debug = logger.debug if log else lambda msg: None
use_sudo = as_root and not self.connected_as_root
if use_sudo:
if self._sudo_needs_password and not self.password:
raise TargetStableError('Attempt to use sudo but no password was specified')
command = self.sudo_cmd.format(quote(command))
log_debug(command)
streams = executor(command, timeout=timeout)
if self._sudo_needs_password:
stdin = streams[0]
stdin.write(self.password + '\n')
stdin.flush()
else:
log_debug(command)
streams = executor(command, timeout=timeout)
return streams
def _execute(self, command, timeout=None, as_root=False, strip_colors=True, log=True):
# Merge stderr into stdout since we are going without a TTY
command = '({}) 2>&1'.format(command)
stdin, stdout, stderr = self._execute_command(
command,
as_root=as_root,
log=log,
timeout=timeout,
executor=self.client.exec_command,
)
stdin.close()
# Empty the stdout buffer of the command, allowing it to carry on to
# completion
def callback(output_chunks, name, chunk):
output_chunks.append(chunk)
return output_chunks
select_timeout = 1
output_chunks, exit_code = _read_paramiko_streams(stdout, stderr, select_timeout, callback, [])
# Join in one go to avoid O(N^2) concatenation
output = b''.join(output_chunks)
output = output.decode(sys.stdout.encoding or 'utf-8', 'replace')
return (exit_code, output)
class TelnetConnection(SshConnectionBase):
default_password_prompt = '[sudo] password'
max_cancel_attempts = 5
# pylint: disable=unused-argument,super-init-not-called
def __init__(self,
host,
username,
password=None,
port=None,
timeout=None,
password_prompt=None,
original_prompt=None,
sudo_cmd="sudo -- sh -c {}",
strict_host_check=True,
platform=None):
super().__init__(
host=host,
username=username,
password=password,
keyfile=None,
port=port,
platform=platform,
sudo_cmd=sudo_cmd,
strict_host_check=strict_host_check,
)
self.options = self._get_default_options()
self.lock = threading.Lock()
self.password_prompt = password_prompt if password_prompt is not None else self.default_password_prompt
logger.debug('Logging in {}@{}'.format(username, host))
timeout = timeout if timeout is not None else self.default_timeout
self.conn = telnet_get_shell(host, username, password, port, timeout, original_prompt)
def fmt_remote_path(self, path):
return '{}@{}:{}'.format(self.username, self.host, path)
def _get_default_options(self):
check = self.strict_host_check
known_hosts = _resolve_known_hosts(check)
return {
'StrictHostKeyChecking': 'yes' if check else 'no',
'UserKnownHostsFile': str(known_hosts),
}
def push(self, sources, dest, timeout=30):
# Quote the destination as SCP would apply globbing too
dest = self.fmt_remote_path(quote(dest))
paths = list(sources) + [dest]
return self._scp(paths, timeout)
def pull(self, sources, dest, timeout=30):
# First level of escaping for the remote shell
sources = ' '.join(map(quote, sources))
# All the sources are merged into one scp parameter
sources = self.fmt_remote_path(sources)
paths = [sources, dest]
self._scp(paths, timeout)
def _scp(self, paths, timeout=30):
# NOTE: the version of scp in Ubuntu 12.04 occasionally (and bizarrely)
# fails to connect to a device if port is explicitly specified using -P
# option, even if it is the default port, 22. To minimize this problem,
# only specify -P for scp if the port is *not* the default.
port_string = '-P {}'.format(quote(str(self.port))) if (self.port and self.port != 22) else ''
keyfile_string = '-i {}'.format(quote(self.keyfile)) if self.keyfile else ''
options = " ".join(["-o {}={}".format(key, val)
for key, val in self.options.items()])
paths = ' '.join(map(quote, paths))
command = '{} {} -r {} {} {}'.format(_SSH_ENV.get_path('scp'),
options,
keyfile_string,
port_string,
paths)
command_redacted = command
logger.debug(command)
if self.password:
command, command_redacted = _give_password(self.password, command)
try:
check_output(command, timeout=timeout, shell=True)
except subprocess.CalledProcessError as e:
msg = f"Failed to copy file with '{command_redacted}'. Output:\n{e.output}"
raise HostError(msg) from None
except TimeoutError as e:
raise TimeoutError(command_redacted, e.output)
def execute(self, command, timeout=None, check_exit_code=True,
as_root=False, strip_colors=True, will_succeed=False): #pylint: disable=unused-argument
if command == '':
# Empty command is valid but the __devlib_ec stuff below will
# produce a syntax error with bash. Treat as a special case.
return ''
try:
with self.lock:
_command = '({}); __devlib_ec=$?; echo; echo $__devlib_ec'.format(command)
full_output = self._execute_and_wait_for_prompt(_command, timeout, as_root, strip_colors)
split_output = full_output.rsplit('\r\n', 2)
try:
output, exit_code_text, _ = split_output
except ValueError as e:
raise TargetStableError(
"cannot split reply (target misconfiguration?):\n'{}'".format(full_output))
if check_exit_code:
try:
exit_code = int(exit_code_text)
except (ValueError, IndexError):
raise ValueError(
'Could not get exit code for "{}",\ngot: "{}"'\
.format(command, exit_code_text))
if exit_code:
cls = TargetTransientCalledProcessError if will_succeed else TargetStableCalledProcessError
raise cls(
exit_code,
command,
output,
None,
)
return output
except EOF:
raise TargetNotRespondingError('Connection lost.')
except TargetCalledProcessError:
raise
except TargetStableError as e:
if will_succeed:
raise TargetTransientError(e)
else:
raise
def background(self, command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, as_root=False):
try:
port_string = '-p {}'.format(self.port) if self.port else ''
keyfile_string = '-i {}'.format(self.keyfile) if self.keyfile else ''
if as_root and not self.connected_as_root:
command = self.sudo_cmd.format(command)
options = " ".join([ "-o {}={}".format(key,val)
for key,val in self.options.items()])
command = '{} {} {} {} {}@{} {}'.format(_SSH_ENV.get_path('ssh'),
options,
keyfile_string,
port_string,
self.username,
self.host,
command)
logger.debug(command)
if self.password:
command, _ = _give_password(self.password, command)
return subprocess.Popen(command, stdout=stdout, stderr=stderr, shell=True)