-
Notifications
You must be signed in to change notification settings - Fork 192
/
Copy pathssh.py
1558 lines (1318 loc) · 61.5 KB
/
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
# -*- coding: utf-8 -*-
###########################################################################
# Copyright (c), The AiiDA team. All rights reserved. #
# This file is part of the AiiDA code. #
# #
# The code is hosted on GitHub at https://github.com/aiidateam/aiida-core #
# For further information on the license, see the LICENSE.txt file #
# For further information please visit http://www.aiida.net #
###########################################################################
"""Plugin for transport over SSH (and SFTP for file transfer)."""
# pylint: disable=too-many-lines
import glob
import io
import os
import re
from stat import S_ISDIR, S_ISREG
import click
import paramiko
from aiida.cmdline.params import options
from aiida.cmdline.params.types.path import AbsolutePathOrEmptyParamType
from aiida.common.escaping import escape_for_bash
from ..transport import Transport, TransportInternalError
__all__ = ('parse_sshconfig', 'convert_to_bool', 'SshTransport')
def parse_sshconfig(computername):
"""
Return the ssh configuration for a given computer name.
This parses the ``.ssh/config`` file in the home directory and
returns the part of configuration of the given computer name.
:param computername: the computer name for which we want the configuration.
"""
config = paramiko.SSHConfig()
try:
with open(os.path.expanduser('~/.ssh/config'), encoding='utf8') as fhandle:
config.parse(fhandle)
except IOError:
# No file found, so empty configuration
pass
return config.lookup(computername)
def convert_to_bool(string):
"""
Convert a string passed in the CLI to a valid bool.
:return: the parsed bool value.
:raise ValueError: If the value is not parsable as a bool
"""
upstring = str(string).upper()
if upstring in ['Y', 'YES', 'T', 'TRUE']:
return True
if upstring in ['N', 'NO', 'F', 'FALSE']:
return False
raise ValueError('Invalid boolean value provided')
class SshTransport(Transport): # pylint: disable=too-many-public-methods
"""
Support connection, command execution and data transfer to remote computers via SSH+SFTP.
"""
# Valid keywords accepted by the connect method of paramiko.SSHClient
# I disable 'password' and 'pkey' to avoid these data to get logged in the
# aiida log file.
_valid_connect_options = [
(
'username', {
'prompt': 'User name',
'help': 'Login user name on the remote machine.',
'non_interactive_default': True
}
),
(
'port',
{
'option': options.PORT,
'prompt': 'Port number',
'non_interactive_default': True,
},
),
(
'look_for_keys', {
'default': True,
'switch': True,
'prompt': 'Look for keys',
'help': 'Automatically look for private keys in the ~/.ssh folder.',
'non_interactive_default': True
}
),
(
'key_filename', {
'type': AbsolutePathOrEmptyParamType(dir_okay=False, exists=True),
'prompt': 'SSH key file',
'help': 'Absolute path to your private SSH key. Leave empty to use the path set in the SSH config.',
'non_interactive_default': True
}
),
(
'timeout', {
'type': int,
'prompt': 'Connection timeout in s',
'help': 'Time in seconds to wait for connection before giving up. Leave empty to use default value.',
'non_interactive_default': True
}
),
(
'allow_agent', {
'default': False,
'switch': True,
'prompt': 'Allow ssh agent',
'help': 'Switch to allow or disallow using an SSH agent.',
'non_interactive_default': True
}
),
(
'proxy_jump', {
'prompt':
'SSH proxy jump',
'help':
'SSH proxy jump for tunneling through other SSH hosts.'
' Use a comma-separated list of hosts of the form [user@]host[:port].'
' If user or port are not specified for a host, the user & port values from the target host are used.'
' This option must be provided explicitly and is not parsed from the SSH config file when left empty.',
'non_interactive_default':
True
}
), # Managed 'manually' in connect
(
'proxy_command', {
'prompt':
'SSH proxy command',
'help':
'SSH proxy command for tunneling through a proxy server.'
' For tunneling through another SSH host, consider using the "SSH proxy jump" option instead!'
' Leave empty to parse the proxy command from the SSH config file.',
'non_interactive_default':
True
}
), # Managed 'manually' in connect
(
'compress', {
'default': True,
'switch': True,
'prompt': 'Compress file transfers',
'help': 'Turn file transfer compression on or off.',
'non_interactive_default': True
}
),
(
'gss_auth', {
'default': False,
'type': bool,
'prompt': 'GSS auth',
'help': 'Enable when using GSS kerberos token to connect.',
'non_interactive_default': True
}
),
(
'gss_kex', {
'default': False,
'type': bool,
'prompt': 'GSS kex',
'help': 'GSS kex for kerberos, if not configured in SSH config file.',
'non_interactive_default': True
}
),
(
'gss_deleg_creds', {
'default': False,
'type': bool,
'prompt': 'GSS deleg_creds',
'help': 'GSS deleg_creds for kerberos, if not configured in SSH config file.',
'non_interactive_default': True
}
),
(
'gss_host', {
'prompt': 'GSS host',
'help': 'GSS host for kerberos, if not configured in SSH config file.',
'non_interactive_default': True
}
),
# for Kerberos support through python-gssapi
]
_valid_connect_params = [i[0] for i in _valid_connect_options]
# Valid parameters for the ssh transport
# For each param, a class method with name
# _convert_PARAMNAME_fromstring
# should be defined, that returns the value converted from a string to
# a correct type, or raise a ValidationError
#
# moreover, if you want to help in the default configuration, you can
# define a _get_PARAMNAME_suggestion_string
# to return a suggestion; it must accept only one parameter, being a Computer
# instance
_valid_auth_options = _valid_connect_options + [
(
'load_system_host_keys', {
'default': True,
'switch': True,
'prompt': 'Load system host keys',
'help': 'Load system host keys from default SSH location.',
'non_interactive_default': True
}
),
(
'key_policy', {
'default': 'RejectPolicy',
'type': click.Choice(['RejectPolicy', 'WarningPolicy', 'AutoAddPolicy']),
'prompt': 'Key policy',
'help': 'SSH key policy if host is not known.',
'non_interactive_default': True
}
)
]
# Max size of log message to print in _exec_command_internal.
# Unlimited by default, but can be cropped by a subclass
# if too large commands are sent, clogging the outputs or logs
_MAX_EXEC_COMMAND_LOG_SIZE = None
@classmethod
def _get_username_suggestion_string(cls, computer):
"""
Return a suggestion for the specific field.
"""
import getpass
config = parse_sshconfig(computer.hostname)
# Either the configured user in the .ssh/config, or the current username
return str(config.get('user', getpass.getuser()))
@classmethod
def _get_port_suggestion_string(cls, computer):
"""
Return a suggestion for the specific field.
"""
config = parse_sshconfig(computer.hostname)
# Either the configured user in the .ssh/config, or the default SSH port
return str(config.get('port', 22))
@classmethod
def _get_key_filename_suggestion_string(cls, computer):
"""
Return a suggestion for the specific field.
"""
config = parse_sshconfig(computer.hostname)
try:
identities = config['identityfile']
# In paramiko > 0.10, identity file is a list of strings.
if isinstance(identities, str):
identity = identities
elif isinstance(identities, (list, tuple)):
if not identities:
# An empty list should not be provided; to be sure,
# anyway, behave as if no identityfile were defined
raise KeyError
# By default we suggest only the first one
identity = identities[0]
else:
# If the parser provides an unknown type, just skip to
# the 'except KeyError' section, as if no identityfile
# were provided (hopefully, this should never happen)
raise KeyError
except KeyError:
# No IdentityFile defined: return an empty string
return ''
return os.path.expanduser(identity)
@classmethod
def _get_timeout_suggestion_string(cls, computer):
"""
Return a suggestion for the specific field.
Provide 60s as a default timeout for connections.
"""
config = parse_sshconfig(computer.hostname)
return str(config.get('connecttimeout', '60'))
@classmethod
def _get_allow_agent_suggestion_string(cls, computer):
"""
Return a suggestion for the specific field.
"""
config = parse_sshconfig(computer.hostname)
return convert_to_bool(str(config.get('allow_agent', 'yes')))
@classmethod
def _get_look_for_keys_suggestion_string(cls, computer):
"""
Return a suggestion for the specific field.
"""
config = parse_sshconfig(computer.hostname)
return convert_to_bool(str(config.get('look_for_keys', 'yes')))
@classmethod
def _get_proxy_command_suggestion_string(cls, computer):
"""
Return a suggestion for the specific field.
"""
config = parse_sshconfig(computer.hostname)
# Either the configured user in the .ssh/config, or the default SSH port
raw_string = str(config.get('proxycommand', ''))
# Note: %h and %p get already automatically substituted with
# hostname and port by the config parser!
pieces = raw_string.split()
new_pieces = []
for piece in pieces:
if '>' in piece:
# If there is a piece with > to readdress stderr or stdout,
# skip from here on (anything else can only be readdressing)
break
new_pieces.append(piece)
return ' '.join(new_pieces)
@classmethod
def _get_proxy_jump_suggestion_string(cls, _):
"""
Return an empty suggestion since Paramiko does not parse ProxyJump from the SSH config.
"""
return ''
@classmethod
def _get_compress_suggestion_string(cls, computer): # pylint: disable=unused-argument
"""
Return a suggestion for the specific field.
"""
return 'True'
@classmethod
def _get_load_system_host_keys_suggestion_string(cls, computer): # pylint: disable=unused-argument
"""
Return a suggestion for the specific field.
"""
return 'True'
@classmethod
def _get_key_policy_suggestion_string(cls, computer): # pylint: disable=unused-argument
"""
Return a suggestion for the specific field.
"""
return 'RejectPolicy'
@classmethod
def _get_gss_auth_suggestion_string(cls, computer):
"""
Return a suggestion for the specific field.
"""
config = parse_sshconfig(computer.hostname)
return convert_to_bool(str(config.get('gssapiauthentication', 'no')))
@classmethod
def _get_gss_kex_suggestion_string(cls, computer):
"""
Return a suggestion for the specific field.
"""
config = parse_sshconfig(computer.hostname)
return convert_to_bool(str(config.get('gssapikeyexchange', 'no')))
@classmethod
def _get_gss_deleg_creds_suggestion_string(cls, computer):
"""
Return a suggestion for the specific field.
"""
config = parse_sshconfig(computer.hostname)
return convert_to_bool(str(config.get('gssapidelegatecredentials', 'no')))
@classmethod
def _get_gss_host_suggestion_string(cls, computer):
"""
Return a suggestion for the specific field.
"""
config = parse_sshconfig(computer.hostname)
return str(config.get('gssapihostname', computer.hostname))
def __init__(self, *args, **kwargs):
"""
Initialize the SshTransport class.
:param machine: the machine to connect to
:param load_system_host_keys: (optional, default False)
if False, do not load the system host keys
:param key_policy: (optional, default = paramiko.RejectPolicy())
the policy to use for unknown keys
Other parameters valid for the ssh connect function (see the
self._valid_connect_params list) are passed to the connect
function (as port, username, password, ...); taken from the
accepted paramiko.SSHClient.connect() params.
"""
super().__init__(*args, **kwargs)
self._sftp = None
self._proxy = None
self._proxies = []
self._machine = kwargs.pop('machine')
self._client = paramiko.SSHClient()
self._load_system_host_keys = kwargs.pop('load_system_host_keys', False)
if self._load_system_host_keys:
self._client.load_system_host_keys()
self._missing_key_policy = kwargs.pop('key_policy', 'RejectPolicy') # This is paramiko default
if self._missing_key_policy == 'RejectPolicy':
self._client.set_missing_host_key_policy(paramiko.RejectPolicy())
elif self._missing_key_policy == 'WarningPolicy':
self._client.set_missing_host_key_policy(paramiko.WarningPolicy())
elif self._missing_key_policy == 'AutoAddPolicy':
self._client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
else:
raise ValueError(
'Unknown value of the key policy, allowed values '
'are: RejectPolicy, WarningPolicy, AutoAddPolicy'
)
self._connect_args = {}
for k in self._valid_connect_params:
try:
self._connect_args[k] = kwargs.pop(k)
except KeyError:
pass
def open(self): # pylint: disable=too-many-branches,too-many-statements
"""
Open a SSHClient to the machine possibly using the parameters given
in the __init__.
Also opens a sftp channel, ready to be used.
The current working directory is set explicitly, so it is not None.
:raise aiida.common.InvalidOperation: if the channel is already open
"""
from paramiko.ssh_exception import SSHException
from aiida.common.exceptions import InvalidOperation
from aiida.transports.util import _DetachedProxyCommand
if self._is_open:
raise InvalidOperation('Cannot open the transport twice')
# Open a SSHClient
connection_arguments = self._connect_args.copy()
if 'key_filename' in connection_arguments and not connection_arguments['key_filename']:
connection_arguments.pop('key_filename')
proxyjumpstring = connection_arguments.pop('proxy_jump', None)
proxycmdstring = connection_arguments.pop('proxy_command', None)
if proxyjumpstring and proxycmdstring:
raise ValueError('The SSH proxy jump and SSH proxy command options can not be used together')
if proxyjumpstring:
matcher = re.compile(r'^(?:(?P<username>[^@]+)@)?(?P<host>[^@:]+)(?::(?P<port>\d+))?\s*$')
try:
# don't use a generator here to have everything evaluated
proxies = [matcher.match(s).groupdict() for s in proxyjumpstring.split(',')]
except AttributeError:
raise ValueError('The given configuration for the SSH proxy jump option could not be parsed')
# proxy_jump supports a list of jump hosts, each jump host is another Paramiko SSH connection
# but when opening a forward channel on a connection, we have to give the next hop.
# So we go through adjacent pairs and by adding the final target to the list we make it universal.
for proxy, target in zip(
proxies, proxies[1:] + [{
'host': self._machine,
'port': connection_arguments.get('port', 22),
}]
):
proxy_connargs = connection_arguments.copy()
if proxy['username']:
proxy_connargs['username'] = proxy['username']
if proxy['port']:
proxy_connargs['port'] = int(proxy['port'])
if not target['port']: # the target port for the channel can not be None
target['port'] = connection_arguments.get('port', 22)
proxy_client = paramiko.SSHClient()
if self._load_system_host_keys:
proxy_client.load_system_host_keys()
if self._missing_key_policy == 'RejectPolicy':
proxy_client.set_missing_host_key_policy(paramiko.RejectPolicy())
elif self._missing_key_policy == 'WarningPolicy':
proxy_client.set_missing_host_key_policy(paramiko.WarningPolicy())
elif self._missing_key_policy == 'AutoAddPolicy':
proxy_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
proxy_client.connect(proxy['host'], **proxy_connargs)
except Exception as exc:
self.logger.error(
f"Error connecting to proxy '{proxy['host']}' through SSH: [{self.__class__.__name__}] {exc}, "
f'connect_args were: {proxy_connargs}'
)
self._close_proxies() # close all since we're going to start anew on the next open() (if any)
raise
connection_arguments['sock'] = proxy_client.get_transport().open_channel(
'direct-tcpip', (target['host'], target['port']), ('', 0)
)
self._proxies.append(proxy_client)
if proxycmdstring:
self._proxy = _DetachedProxyCommand(proxycmdstring)
connection_arguments['sock'] = self._proxy
try:
self._client.connect(self._machine, **connection_arguments)
except Exception as exc:
self.logger.error(
f"Error connecting to '{self._machine}' through SSH: " + f'[{self.__class__.__name__}] {exc}, ' +
f'connect_args were: {self._connect_args}'
)
self._close_proxies()
raise
# Open the SFTP channel, and handle error by directing customer to try another transport
try:
self._sftp = self._client.open_sftp()
except SSHException:
self._close_proxies()
raise InvalidOperation(
'Error in ssh transport plugin. This may be due to the remote computer not supporting SFTP. '
'Try setting it up with the aiida.transports:ssh_only transport from the aiida-sshonly plugin instead.'
)
self._is_open = True
# Set the current directory to a explicit path, and not to None
self._sftp.chdir(self._sftp.normalize('.'))
return self
def _close_proxies(self):
"""Close all proxy connections (proxy_jump and proxy_command)"""
# Paramiko only closes the channel when closing the main connection, but not the connection itself.
while self._proxies:
self._proxies.pop().close()
if self._proxy:
# Paramiko should close this automatically when closing the channel,
# but since the process is started in __init__this might not happen correctly.
self._proxy.close()
self._proxy = None
def close(self):
"""
Close the SFTP channel, and the SSHClient.
:todo: correctly manage exceptions
:raise aiida.common.InvalidOperation: if the channel is already open
"""
from aiida.common.exceptions import InvalidOperation
if not self._is_open:
raise InvalidOperation('Cannot close the transport: it is already closed')
self._sftp.close()
self._client.close()
self._close_proxies()
self._is_open = False
@property
def sshclient(self):
if not self._is_open:
raise TransportInternalError('Error, ssh method called for SshTransport without opening the channel first')
return self._client
@property
def sftp(self):
if not self._is_open:
raise TransportInternalError('Error, sftp method called for SshTransport without opening the channel first')
return self._sftp
def __str__(self):
"""
Return a useful string.
"""
conn_info = self._machine
try:
conn_info = f"{self._connect_args['username']}@{conn_info}"
except KeyError:
# No username explicitly defined: ignore
pass
try:
conn_info += f":{self._connect_args['port']}"
except KeyError:
# No port explicitly defined: ignore
pass
return f"{'OPEN' if self._is_open else 'CLOSED'} [{conn_info}]"
def chdir(self, path):
"""
Change directory of the SFTP session. Emulated internally by paramiko.
Differently from paramiko, if you pass None to chdir, nothing
happens and the cwd is unchanged.
"""
from paramiko.sftp import SFTPError
old_path = self.sftp.getcwd()
if path is not None:
try:
self.sftp.chdir(path)
except SFTPError as exc:
# e.args[0] is an error code. For instance,
# 20 is 'the object is not a directory'
# Here I just re-raise the message as IOError
raise IOError(exc.args[1])
# Paramiko already checked that path is a folder, otherwise I would
# have gotten an exception. Now, I want to check that I have read
# permissions in this folder (nothing is said on write permissions,
# though).
# Otherwise, if I do _exec_command_internal, that as a first operation
# cd's in a folder, I get a wrong retval, that is an unwanted behavior.
#
# Note: I don't store the result of the function; if I have no
# read permissions, this will raise an exception.
try:
self.stat('.')
except IOError as exc:
if 'Permission denied' in str(exc):
self.chdir(old_path)
raise IOError(str(exc))
def normalize(self, path='.'):
"""
Returns the normalized path (removing double slashes, etc...)
"""
return self.sftp.normalize(path)
def stat(self, path):
"""
Retrieve information about a file on the remote system. The return
value is an object whose attributes correspond to the attributes of
Python's ``stat`` structure as returned by ``os.stat``, except that it
contains fewer fields.
The fields supported are: ``st_mode``, ``st_size``, ``st_uid``,
``st_gid``, ``st_atime``, and ``st_mtime``.
:param str path: the filename to stat
:return: a `paramiko.sftp_attr.SFTPAttributes` object containing
attributes about the given file.
"""
return self.sftp.stat(path)
def lstat(self, path):
"""
Retrieve information about a file on the remote system, without
following symbolic links (shortcuts). This otherwise behaves exactly
the same as `stat`.
:param str path: the filename to stat
:return: a `paramiko.sftp_attr.SFTPAttributes` object containing
attributes about the given file.
"""
return self.sftp.lstat(path)
def getcwd(self):
"""
Return the current working directory for this SFTP session, as
emulated by paramiko. If no directory has been set with chdir,
this method will return None. But in __enter__ this is set explicitly,
so this should never happen within this class.
"""
return self.sftp.getcwd()
def makedirs(self, path, ignore_existing=False):
"""
Super-mkdir; create a leaf directory and all intermediate ones.
Works like mkdir, except that any intermediate path segment (not
just the rightmost) will be created if it does not exist.
NOTE: since os.path.split uses the separators as the host system
(that could be windows), I assume the remote computer is Linux-based
and use '/' as separators!
:param path: directory to create (string)
:param ignore_existing: if set to true, it doesn't give any error
if the leaf directory does already exist (bool)
:raise OSError: If the directory already exists.
"""
# check to avoid creation of empty dirs
path = os.path.normpath(path)
if path.startswith('/'):
to_create = path.strip().split('/')[1:]
this_dir = '/'
else:
to_create = path.strip().split('/')
this_dir = ''
for count, element in enumerate(to_create):
if count > 0:
this_dir += '/'
this_dir += element
if count + 1 == len(to_create) and self.isdir(this_dir) and ignore_existing:
return
if count + 1 == len(to_create) and self.isdir(this_dir) and not ignore_existing:
self.mkdir(this_dir)
if not self.isdir(this_dir):
self.mkdir(this_dir)
def mkdir(self, path, ignore_existing=False):
"""
Create a folder (directory) named path.
:param path: name of the folder to create
:param ignore_existing: if True, does not give any error if the directory
already exists
:raise OSError: If the directory already exists.
"""
if ignore_existing and self.isdir(path):
return
try:
self.sftp.mkdir(path)
except IOError as exc:
if os.path.isabs(path):
raise OSError(
"Error during mkdir of '{}', "
"maybe you don't have the permissions to do it, "
'or the directory already exists? ({})'.format(path, exc)
)
else:
raise OSError(
"Error during mkdir of '{}' from folder '{}', "
"maybe you don't have the permissions to do it, "
'or the directory already exists? ({})'.format(path, self.getcwd(), exc)
)
def rmtree(self, path):
"""
Remove a file or a directory at path, recursively
Flags used: -r: recursive copy; -f: force, makes the command non interactive;
:param path: remote path to delete
:raise IOError: if the rm execution failed.
"""
# Assuming linux rm command!
rm_exe = 'rm'
rm_flags = '-r -f'
# if in input I give an invalid object raise ValueError
if not path:
raise ValueError('Input to rmtree() must be a non empty string. ' + f'Found instead {path} as path')
command = f'{rm_exe} {rm_flags} {escape_for_bash(path)}'
retval, stdout, stderr = self.exec_command_wait_bytes(command)
if retval == 0:
if stderr.strip():
self.logger.warning(f'There was nonempty stderr in the rm command: {stderr}')
return True
self.logger.error(f"Problem executing rm. Exit code: {retval}, stdout: '{stdout}', stderr: '{stderr}'")
raise IOError(f'Error while executing rm. Exit code: {retval}')
def rmdir(self, path):
"""
Remove the folder named 'path' if empty.
"""
self.sftp.rmdir(path)
def chown(self, path, uid, gid):
"""
Change owner permissions of a file.
For now, this is not implemented for the SSH transport.
"""
raise NotImplementedError
def isdir(self, path):
"""
Return True if the given path is a directory, False otherwise.
Return False also if the path does not exist.
"""
# Return False on empty string (paramiko would map this to the local
# folder instead)
if not path:
return False
try:
return S_ISDIR(self.stat(path).st_mode)
except IOError as exc:
if getattr(exc, 'errno', None) == 2:
# errno=2 means path does not exist: I return False
return False
raise # Typically if I don't have permissions (errno=13)
def chmod(self, path, mode):
"""
Change permissions to path
:param path: path to file
:param mode: new permission bits (integer)
"""
if not path:
raise IOError('Input path is an empty argument.')
return self.sftp.chmod(path, mode)
@staticmethod
def _os_path_split_asunder(path):
"""
Used by makedirs. Takes path (a str)
and returns a list deconcatenating the path
"""
parts = []
while True:
newpath, tail = os.path.split(path)
if newpath == path:
assert not tail
if path:
parts.append(path)
break
parts.append(tail)
path = newpath
parts.reverse()
return parts
def put(self, localpath, remotepath, callback=None, dereference=True, overwrite=True, ignore_nonexisting=False): # pylint: disable=too-many-arguments,too-many-branches,arguments-differ
"""
Put a file or a folder from local to remote.
Redirects to putfile or puttree.
:param localpath: an (absolute) local path
:param remotepath: a remote path
:param dereference: follow symbolic links (boolean).
Default = True (default behaviour in paramiko). False is not implemented.
:param overwrite: if True overwrites files and folders (boolean).
Default = False.
:raise ValueError: if local path is invalid
:raise OSError: if the localpath does not exist
"""
if not dereference:
raise NotImplementedError
if not os.path.isabs(localpath):
raise ValueError('The localpath must be an absolute path')
if self.has_magic(localpath):
if self.has_magic(remotepath):
raise ValueError('Pathname patterns are not allowed in the destination')
# use the imported glob to analyze the path locally
to_copy_list = glob.glob(localpath)
rename_remote = False
if len(to_copy_list) > 1:
# I can't scp more than one file on a single file
if self.isfile(remotepath):
raise OSError('Remote destination is not a directory')
# I can't scp more than one file in a non existing directory
elif not self.path_exists(remotepath): # questo dovrebbe valere solo per file
raise OSError('Remote directory does not exist')
else: # the remote path is a directory
rename_remote = True
for file in to_copy_list:
if os.path.isfile(file):
if rename_remote: # copying more than one file in one directory
# here is the case isfile and more than one file
remotefile = os.path.join(remotepath, os.path.split(file)[1])
self.putfile(file, remotefile, callback, dereference, overwrite)
elif self.isdir(remotepath): # one file to copy in '.'
remotefile = os.path.join(remotepath, os.path.split(file)[1])
self.putfile(file, remotefile, callback, dereference, overwrite)
else: # one file to copy on one file
self.putfile(file, remotepath, callback, dereference, overwrite)
else:
self.puttree(file, remotepath, callback, dereference, overwrite)
else:
if os.path.isdir(localpath):
self.puttree(localpath, remotepath, callback, dereference, overwrite)
elif os.path.isfile(localpath):
if self.isdir(remotepath):
remote = os.path.join(remotepath, os.path.split(localpath)[1])
self.putfile(localpath, remote, callback, dereference, overwrite)
else:
self.putfile(localpath, remotepath, callback, dereference, overwrite)
else:
if not ignore_nonexisting:
raise OSError(f'The local path {localpath} does not exist')
def putfile(self, localpath, remotepath, callback=None, dereference=True, overwrite=True): # pylint: disable=arguments-differ
"""
Put a file from local to remote.
:param localpath: an (absolute) local path
:param remotepath: a remote path
:param overwrite: if True overwrites files and folders (boolean).
Default = True.
:raise ValueError: if local path is invalid
:raise OSError: if the localpath does not exist,
or unintentionally overwriting
"""
if not dereference:
raise NotImplementedError
if not os.path.isabs(localpath):
raise ValueError('The localpath must be an absolute path')
if self.isfile(remotepath) and not overwrite:
raise OSError('Destination already exists: not overwriting it')
return self.sftp.put(localpath, remotepath, callback=callback)
def puttree(self, localpath, remotepath, callback=None, dereference=True, overwrite=True): # pylint: disable=too-many-branches,arguments-differ,unused-argument
"""
Put a folder recursively from local to remote.
By default, overwrite.
:param localpath: an (absolute) local path
:param remotepath: a remote path
:param dereference: follow symbolic links (boolean)
Default = True (default behaviour in paramiko). False is not implemented.
:param overwrite: if True overwrites files and folders (boolean).
Default = True
:raise ValueError: if local path is invalid
:raise OSError: if the localpath does not exist, or trying to overwrite
:raise IOError: if remotepath is invalid
.. note:: setting dereference equal to True could cause infinite loops.
see os.walk() documentation
"""
if not dereference:
raise NotImplementedError
if not os.path.isabs(localpath):
raise ValueError('The localpath must be an absolute path')
if not os.path.exists(localpath):
raise OSError('The localpath does not exists')
if not os.path.isdir(localpath):
raise ValueError(f'Input localpath is not a folder: {localpath}')
if not remotepath:
raise IOError('remotepath must be a non empty string')
if self.path_exists(remotepath) and not overwrite:
raise OSError("Can't overwrite existing files")
if self.isfile(remotepath):
raise OSError('Cannot copy a directory into a file')
if not self.isdir(remotepath): # in this case copy things in the remotepath directly
self.mkdir(remotepath) # and make a directory at its place
else: # remotepath exists already: copy the folder inside of it!
remotepath = os.path.join(remotepath, os.path.split(localpath)[1])
self.mkdir(remotepath) # create a nested folder
for this_source in os.walk(localpath):
# Get the relative path
this_basename = os.path.relpath(path=this_source[0], start=localpath)
try:
self.stat(os.path.join(remotepath, this_basename))
except IOError as exc:
import errno
if exc.errno == errno.ENOENT: # Missing file
self.mkdir(os.path.join(remotepath, this_basename))
else:
raise
for this_file in this_source[2]:
this_local_file = os.path.join(localpath, this_basename, this_file)
this_remote_file = os.path.join(remotepath, this_basename, this_file)
self.putfile(this_local_file, this_remote_file)
def get(self, remotepath, localpath, callback=None, dereference=True, overwrite=True, ignore_nonexisting=False): # pylint: disable=too-many-branches,arguments-differ,too-many-arguments
"""
Get a file or folder from remote to local.