sftpkit 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
sftpkit/__init__.py ADDED
@@ -0,0 +1,1063 @@
1
+ """A friendly Python SFTP interface.
2
+
3
+ A maintained, drop-in successor to pysftp 0.2.9. See DECISIONS.md.
4
+ """
5
+ from __future__ import print_function
6
+
7
+ import os
8
+ from contextlib import contextmanager
9
+ import posixpath
10
+ import socket
11
+ from stat import S_IMODE, S_ISDIR, S_ISREG
12
+ import tempfile
13
+ import warnings
14
+
15
+ import paramiko
16
+ from paramiko import SSHException, AuthenticationException # make available
17
+ from paramiko import AgentKey, PKey, RSAKey
18
+
19
+ from .exceptions import (CredentialException, ConnectionException,
20
+ HostKeysException)
21
+ from .helpers import (st_mode_to_int, WTCallbacks, path_advance,
22
+ path_retreat, reparent, walktree, cd, known_hosts)
23
+
24
+ # paramiko 4 removed DSA keys. Keep the name where it still exists, so code
25
+ # that used pysftp.DSSKey on an older paramiko keeps working.
26
+ DSSKey = getattr(paramiko, "DSSKey", None)
27
+
28
+ __version__ = "1.0.0"
29
+
30
+ # Default keys, in the order they are tried (DECISIONS.md, D6).
31
+ _DEFAULT_KEYS = ('~/.ssh/id_rsa', '~/.ssh/id_dsa', '~/.ssh/id_ed25519',
32
+ '~/.ssh/id_ecdsa')
33
+
34
+
35
+ def _load_private_key(path, passphrase):
36
+ """Load a private key of any type paramiko supports from a file."""
37
+ try:
38
+ return PKey.from_path(path, passphrase=passphrase)
39
+ except (paramiko.PasswordRequiredException,
40
+ paramiko.AuthenticationException):
41
+ raise
42
+ except (paramiko.SSHException, ValueError, TypeError) as err:
43
+ # PKey.from_path cannot read keys in the old PEM format for every
44
+ # type; fall back to trying each class, as pysftp did.
45
+ for cls_name in ("RSAKey", "Ed25519Key", "ECDSAKey", "DSSKey"):
46
+ cls = getattr(paramiko, cls_name, None)
47
+ if cls is None:
48
+ continue
49
+ try:
50
+ return cls.from_private_key_file(path, passphrase)
51
+ except paramiko.PasswordRequiredException:
52
+ raise
53
+ except paramiko.SSHException:
54
+ continue
55
+ raise paramiko.SSHException(
56
+ "Could not load private key %s: %s" % (path, err))
57
+ # pylint: disable = R0913,C0302
58
+
59
+
60
+ class CnOpts(object): # pylint:disable=r0903
61
+ '''additional connection options beyond authentication
62
+
63
+ :ivar bool|str log: initial value: False -
64
+ log connection/handshake details? If set to True,
65
+ pysftp creates a temporary file and logs to that. If set to a valid
66
+ path and filename, pysftp logs to that. The name of the logfile can
67
+ be found at ``.logfile``
68
+ :ivar bool compression: initial value: False - Enables compression on the
69
+ transport, if set to True.
70
+ :ivar list|None ciphers: initial value: None -
71
+ List of ciphers to use in order.
72
+ :ivar paramiko.hostkeys.HostKeys|None hostkeys: HostKeys object to use for
73
+ host key checking.
74
+ :param filepath|None knownhosts: initial value: None - file to load
75
+ hostkeys. If not specified, uses ~/.ssh/known_hosts
76
+ :returns: (obj) CnOpts - A connection options object, used for passing
77
+ extended options to the Connection
78
+ :raises HostKeysException:
79
+ '''
80
+ def __init__(self, knownhosts=None):
81
+ self.log = False
82
+ self.compression = False
83
+ self.ciphers = None
84
+ if knownhosts is None:
85
+ knownhosts = known_hosts()
86
+ self.hostkeys = paramiko.hostkeys.HostKeys()
87
+ try:
88
+ self.hostkeys.load(knownhosts)
89
+ except IOError:
90
+ # can't find known_hosts in the standard place
91
+ wmsg = "Failed to load HostKeys from %s. " % knownhosts
92
+ wmsg += "You will need to explicitly load HostKeys "
93
+ wmsg += "(cnopts.hostkeys.load(filename)) or disable "
94
+ wmsg += "HostKey checking (cnopts.hostkeys = None)."
95
+ warnings.warn(wmsg, UserWarning)
96
+ else:
97
+ if len(self.hostkeys.items()) == 0:
98
+ raise HostKeysException('No Host Keys Found')
99
+
100
+ def get_hostkey(self, host, port=22):
101
+ '''return the matching hostkey to use for verification for the host
102
+ indicated or raise an SSHException
103
+
104
+ OpenSSH saves a server on a port other than 22 as ``[host]:port``;
105
+ that entry is tried first, then the bare host name.'''
106
+ kval = None
107
+ if port != 22:
108
+ kval = self.hostkeys.lookup("[%s]:%d" % (host, port))
109
+ if kval is None:
110
+ kval = self.hostkeys.lookup(host) # None|{keytype: PKey}
111
+ if kval is None:
112
+ raise SSHException("No hostkey for host %s found." % host)
113
+ # return the pkey from the dict
114
+ return list(kval.values())[0]
115
+
116
+
117
+ class Connection(object): # pylint:disable=r0902,r0904
118
+ """Connects and logs into the specified hostname.
119
+ Arguments that are not given are guessed from the environment.
120
+
121
+ :param str host:
122
+ The Hostname or IP of the remote machine.
123
+ :param str|None username: *Default: None* -
124
+ Your username at the remote machine.
125
+ :param str|obj|None private_key: *Default: None* -
126
+ path to private key file(str) or paramiko.AgentKey
127
+ :param str|None password: *Default: None* -
128
+ Your password at the remote machine.
129
+ :param int port: *Default: 22* -
130
+ The SSH port of the remote machine.
131
+ :param str|None private_key_pass: *Default: None* -
132
+ password to use, if private_key is encrypted.
133
+ :param list|None ciphers: *Deprecated* -
134
+ see ``pysftp.CnOpts`` and ``cnopts`` parameter
135
+ :param bool|str log: *Deprecated* -
136
+ see ``pysftp.CnOpts`` and ``cnopts`` parameter
137
+ :param None|CnOpts cnopts: *Default: None* - extra connection options
138
+ set in a CnOpts object.
139
+ :param str|None default_path: *Default: None* -
140
+ set a default path upon connection.
141
+ :returns: (obj) connection to the requested host
142
+ :raises ConnectionException:
143
+ :raises CredentialException:
144
+ :raises SSHException:
145
+ :raises AuthenticationException:
146
+ :raises PasswordRequiredException:
147
+ :raises HostKeysException:
148
+
149
+ """
150
+
151
+ def __init__(self, host, username=None, private_key=None, password=None,
152
+ port=22, private_key_pass=None, ciphers=None, log=False,
153
+ cnopts=None, default_path=None):
154
+ # Set first, so close() and __del__ work even if connecting fails.
155
+ self._sftp_live = False
156
+ self._sftp = None
157
+ self._transport = None
158
+ self._cnopts = None
159
+ # starting point for transport.connect options
160
+ self._tconnect = {'username': username, 'password': password,
161
+ 'hostkey': None, 'pkey': None}
162
+ self._cnopts = cnopts or CnOpts()
163
+ self._default_path = default_path
164
+ # TODO: remove this if block and log param above in v0.3.0
165
+ if log:
166
+ wmsg = "log parameter is deprecated and will be remove in 0.3.0. "\
167
+ "Use cnopts param."
168
+ warnings.warn(wmsg, DeprecationWarning)
169
+ self._cnopts.log = log
170
+ # TODO: remove this if block and log param above in v0.3.0
171
+ if ciphers is not None:
172
+ wmsg = "ciphers parameter is deprecated and will be remove in "\
173
+ "0.3.0. Use cnopts param."
174
+ warnings.warn(wmsg, DeprecationWarning)
175
+ self._cnopts.ciphers = ciphers
176
+ # check that we have a hostkey to verify
177
+ if self._cnopts.hostkeys is not None:
178
+ self._tconnect['hostkey'] = self._cnopts.get_hostkey(host, port)
179
+
180
+ self._set_username()
181
+ self._set_logging()
182
+ # Begin the SSH transport.
183
+ self._start_transport(host, port)
184
+ self._transport.use_compression(self._cnopts.compression)
185
+ self._set_authentication(password, private_key, private_key_pass)
186
+ self._transport.connect(**self._tconnect)
187
+
188
+ def _set_authentication(self, password, private_key, private_key_pass):
189
+ '''Authenticate the transport. prefer password if given'''
190
+ if password is None:
191
+ # Use Private Key.
192
+ if not private_key:
193
+ # Try to use default key.
194
+ for candidate in _DEFAULT_KEYS:
195
+ if os.path.exists(os.path.expanduser(candidate)):
196
+ private_key = candidate
197
+ break
198
+ else:
199
+ raise CredentialException("No password or key specified.")
200
+
201
+ if isinstance(private_key, (AgentKey, PKey)):
202
+ # use the paramiko agent key, or a key already loaded
203
+ self._tconnect['pkey'] = private_key
204
+ else:
205
+ # build a key from what we assume is a path to a key
206
+ private_key_file = os.path.expanduser(private_key)
207
+ self._tconnect['pkey'] = _load_private_key(
208
+ private_key_file, private_key_pass)
209
+
210
+ def _start_transport(self, host, port):
211
+ '''start the transport and set the ciphers if specified.'''
212
+ try:
213
+ self._transport = paramiko.Transport((host, port))
214
+ # Set security ciphers if set
215
+ if self._cnopts.ciphers is not None:
216
+ ciphers = self._cnopts.ciphers
217
+ self._transport.get_security_options().ciphers = ciphers
218
+ except (AttributeError, socket.gaierror):
219
+ # couldn't connect
220
+ raise ConnectionException(host, port)
221
+
222
+ def _set_username(self):
223
+ '''set the username for the connection. If not passed, then look to the
224
+ environment. Still nothing? Throw exception.'''
225
+ if self._tconnect['username'] is None:
226
+ self._tconnect['username'] = os.environ.get('LOGNAME', None)
227
+ if self._tconnect['username'] is None:
228
+ raise CredentialException('No username specified.')
229
+
230
+ def _set_logging(self):
231
+ '''set logging for connection'''
232
+ if self._cnopts.log:
233
+ if isinstance(self._cnopts.log, bool):
234
+ # Log to a temporary file.
235
+ fhnd, self._cnopts.log = tempfile.mkstemp('.txt', 'ssh-')
236
+ os.close(fhnd) # don't want os file descriptors open
237
+ paramiko.util.log_to_file(self._cnopts.log)
238
+
239
+ def _sftp_connect(self):
240
+ """Establish the SFTP connection."""
241
+ if not self._sftp_live:
242
+ self._sftp = paramiko.SFTPClient.from_transport(self._transport)
243
+ if self._default_path is not None:
244
+ # print("_default_path: [%s]" % self._default_path)
245
+ self._sftp.chdir(self._default_path)
246
+ self._sftp_live = True
247
+
248
+ @property
249
+ def pwd(self):
250
+ '''return the current working directory
251
+
252
+ :returns: (str) current working directory
253
+
254
+ '''
255
+ self._sftp_connect()
256
+ return self._sftp.normalize('.')
257
+
258
+ def get(self, remotepath, localpath=None, callback=None,
259
+ preserve_mtime=False):
260
+ """Copies a file between the remote host and the local host.
261
+
262
+ :param str remotepath: the remote path and filename, source
263
+ :param str localpath:
264
+ the local path and filename to copy, destination. If not specified,
265
+ file is copied to local current working directory
266
+ :param callable callback:
267
+ optional callback function (form: ``func(int, int)``) that accepts
268
+ the bytes transferred so far and the total bytes to be transferred.
269
+ :param bool preserve_mtime:
270
+ *Default: False* - make the modification time(st_mtime) on the
271
+ local file match the time on the remote. (st_atime can differ
272
+ because stat'ing the localfile can/does update it's st_atime)
273
+
274
+ :returns: None
275
+
276
+ :raises: IOError
277
+
278
+ """
279
+ if not localpath:
280
+ localpath = os.path.split(remotepath)[1]
281
+
282
+ self._sftp_connect()
283
+ if preserve_mtime:
284
+ sftpattrs = self._sftp.stat(remotepath)
285
+
286
+ self._sftp.get(remotepath, localpath, callback=callback)
287
+ if preserve_mtime:
288
+ os.utime(localpath, (sftpattrs.st_atime, sftpattrs.st_mtime))
289
+
290
+ def get_d(self, remotedir, localdir, preserve_mtime=False):
291
+ """get the contents of remotedir and write to locadir. (non-recursive)
292
+
293
+ :param str remotedir: the remote directory to copy from (source)
294
+ :param str localdir: the local directory to copy to (target)
295
+ :param bool preserve_mtime: *Default: False* -
296
+ preserve modification time on files
297
+
298
+ :returns: None
299
+
300
+ :raises:
301
+ """
302
+ self._sftp_connect()
303
+ with self.cd(remotedir):
304
+ for sattr in self._sftp.listdir_attr('.'):
305
+ if S_ISREG(sattr.st_mode):
306
+ rname = sattr.filename
307
+ self.get(rname, reparent(localdir, rname),
308
+ preserve_mtime=preserve_mtime)
309
+
310
+ def get_r(self, remotedir, localdir, preserve_mtime=False):
311
+ """recursively copy remotedir structure to localdir
312
+
313
+ :param str remotedir: the remote directory to copy from
314
+ :param str localdir: the local directory to copy to
315
+ :param bool preserve_mtime: *Default: False* -
316
+ preserve modification time on files
317
+
318
+ :returns: None
319
+
320
+ :raises:
321
+
322
+ """
323
+ self._sftp_connect()
324
+ # pysftp needed localdir to exist already, and failed half-way if not
325
+ if not os.path.isdir(localdir):
326
+ os.makedirs(localdir)
327
+ wtcb = WTCallbacks()
328
+ self.walktree(remotedir, wtcb.file_cb, wtcb.dir_cb, wtcb.unk_cb)
329
+ # handle directories we recursed through
330
+ for dname in wtcb.dlist:
331
+ for subdir in path_advance(dname):
332
+ try:
333
+ os.mkdir(reparent(localdir, subdir))
334
+ # force result to a list for setter,
335
+ wtcb.dlist = wtcb.dlist + [subdir, ]
336
+ except OSError: # dir exists
337
+ pass
338
+
339
+ for fname in wtcb.flist:
340
+ # they may have told us to start down farther, so we may not have
341
+ # recursed through some, ensure local dir structure matches
342
+ head, _ = os.path.split(fname)
343
+ if head not in wtcb.dlist:
344
+ for subdir in path_advance(head):
345
+ if subdir not in wtcb.dlist and subdir != '.':
346
+ os.mkdir(reparent(localdir, subdir))
347
+ wtcb.dlist = wtcb.dlist + [subdir, ]
348
+
349
+ self.get(fname,
350
+ reparent(localdir, fname),
351
+ preserve_mtime=preserve_mtime)
352
+
353
+ def getfo(self, remotepath, flo, callback=None):
354
+ """Copy a remote file (remotepath) to a file-like object, flo.
355
+
356
+ :param str remotepath: the remote path and filename, source
357
+ :param flo: open file like object to write, destination.
358
+ :param callable callback:
359
+ optional callback function (form: ``func(int, int``)) that accepts
360
+ the bytes transferred so far and the total bytes to be transferred.
361
+
362
+ :returns: (int) the number of bytes written to the opened file object
363
+
364
+ :raises: Any exception raised by operations will be passed through.
365
+
366
+ """
367
+ self._sftp_connect()
368
+ return self._sftp.getfo(remotepath, flo, callback=callback)
369
+
370
+ def put(self, localpath, remotepath=None, callback=None, confirm=True,
371
+ preserve_mtime=False):
372
+ """Copies a file between the local host and the remote host.
373
+
374
+ :param str localpath: the local path and filename
375
+ :param str remotepath:
376
+ the remote path, else the remote :attr:`.pwd` and filename is used.
377
+ :param callable callback:
378
+ optional callback function (form: ``func(int, int``)) that accepts
379
+ the bytes transferred so far and the total bytes to be transferred.
380
+ :param bool confirm:
381
+ whether to do a stat() on the file afterwards to confirm the file
382
+ size
383
+ :param bool preserve_mtime:
384
+ *Default: False* - make the modification time(st_mtime) on the
385
+ remote file match the time on the local. (st_atime can differ
386
+ because stat'ing the localfile can/does update it's st_atime)
387
+
388
+ :returns:
389
+ (obj) SFTPAttributes containing attributes about the given file
390
+
391
+ :raises IOError: if remotepath doesn't exist
392
+ :raises OSError: if localpath doesn't exist
393
+
394
+ """
395
+ if not remotepath:
396
+ remotepath = os.path.split(localpath)[1]
397
+ self._sftp_connect()
398
+
399
+ if preserve_mtime:
400
+ local_stat = os.stat(localpath)
401
+ times = (local_stat.st_atime, local_stat.st_mtime)
402
+
403
+ sftpattrs = self._sftp.put(localpath, remotepath, callback=callback,
404
+ confirm=confirm)
405
+ if preserve_mtime:
406
+ self._sftp.utime(remotepath, times)
407
+ sftpattrs = self._sftp.stat(remotepath)
408
+
409
+ return sftpattrs
410
+
411
+ def put_d(self, localpath, remotepath, confirm=True, preserve_mtime=False):
412
+ """Copies a local directory's contents to a remotepath
413
+
414
+ :param str localpath: the local path to copy (source)
415
+ :param str remotepath:
416
+ the remote path to copy to (target)
417
+ :param bool confirm:
418
+ whether to do a stat() on the file afterwards to confirm the file
419
+ size
420
+ :param bool preserve_mtime:
421
+ *Default: False* - make the modification time(st_mtime) on the
422
+ remote file match the time on the local. (st_atime can differ
423
+ because stat'ing the localfile can/does update it's st_atime)
424
+
425
+ :returns: None
426
+
427
+ :raises IOError: if remotepath doesn't exist
428
+ :raises OSError: if localpath doesn't exist
429
+ """
430
+ self._sftp_connect()
431
+ wtcb = WTCallbacks()
432
+ cur_local_dir = os.getcwd()
433
+ os.chdir(localpath)
434
+ walktree('.', wtcb.file_cb, wtcb.dir_cb, wtcb.unk_cb,
435
+ recurse=False)
436
+ for fname in wtcb.flist:
437
+ src = os.path.join(localpath, fname)
438
+ dest = reparent(remotepath, fname)
439
+ # print('put', src, dest)
440
+ self.put(src, dest, confirm=confirm, preserve_mtime=preserve_mtime)
441
+
442
+ # restore local directory
443
+ os.chdir(cur_local_dir)
444
+
445
+ def put_r(self, localpath, remotepath, confirm=True, preserve_mtime=False):
446
+ """Recursively copies a local directory's contents to a remotepath
447
+
448
+ :param str localpath: the local path to copy (source)
449
+ :param str remotepath:
450
+ the remote path to copy to (target)
451
+ :param bool confirm:
452
+ whether to do a stat() on the file afterwards to confirm the file
453
+ size
454
+ :param bool preserve_mtime:
455
+ *Default: False* - make the modification time(st_mtime) on the
456
+ remote file match the time on the local. (st_atime can differ
457
+ because stat'ing the localfile can/does update it's st_atime)
458
+
459
+ :returns: None
460
+
461
+ :raises IOError: if remotepath doesn't exist
462
+ :raises OSError: if localpath doesn't exist
463
+ """
464
+ self._sftp_connect()
465
+ wtcb = WTCallbacks()
466
+ cur_local_dir = os.getcwd()
467
+ os.chdir(localpath)
468
+ walktree('.', wtcb.file_cb, wtcb.dir_cb, wtcb.unk_cb)
469
+ # restore local directory
470
+ os.chdir(cur_local_dir)
471
+ for dname in wtcb.dlist:
472
+ if dname != '.':
473
+ pth = reparent(remotepath, dname)
474
+ if not self.isdir(pth):
475
+ self.mkdir(pth)
476
+
477
+ for fname in wtcb.flist:
478
+ head, _ = os.path.split(fname)
479
+ if head not in wtcb.dlist:
480
+ for subdir in path_advance(head):
481
+ if subdir not in wtcb.dlist and subdir != '.':
482
+ self.mkdir(reparent(remotepath, subdir))
483
+ wtcb.dlist = wtcb.dlist + [subdir, ]
484
+ src = os.path.join(localpath, fname)
485
+ dest = reparent(remotepath, fname)
486
+ # print('put', src, dest)
487
+ self.put(src, dest, confirm=confirm, preserve_mtime=preserve_mtime)
488
+
489
+ def putfo(self, flo, remotepath=None, file_size=0, callback=None,
490
+ confirm=True):
491
+
492
+ """Copies the contents of a file like object to remotepath.
493
+
494
+ :param flo: a file-like object that supports .read()
495
+ :param str remotepath: the remote path.
496
+ :param int file_size:
497
+ the size of flo, if not given the second param passed to the
498
+ callback function will always be 0.
499
+ :param callable callback:
500
+ optional callback function (form: ``func(int, int``)) that accepts
501
+ the bytes transferred so far and the total bytes to be transferred.
502
+ :param bool confirm:
503
+ whether to do a stat() on the file afterwards to confirm the file
504
+ size
505
+
506
+ :returns:
507
+ (obj) SFTPAttributes containing attributes about the given file
508
+
509
+ :raises: TypeError, if remotepath not specified, any underlying error
510
+
511
+ """
512
+ self._sftp_connect()
513
+ return self._sftp.putfo(flo, remotepath, file_size=file_size,
514
+ callback=callback, confirm=confirm)
515
+
516
+ def execute(self, command):
517
+ """Execute the given commands on a remote machine. The command is
518
+ executed without regard to the remote :attr:`.pwd`.
519
+
520
+ :param str command: the command to execute.
521
+
522
+ :returns: (list of str) representing the results of the command
523
+
524
+ :raises: Any exception raised by command will be passed through.
525
+
526
+ """
527
+ channel = self._transport.open_session()
528
+ channel.exec_command(command)
529
+ output = channel.makefile('rb', -1).readlines()
530
+ if output:
531
+ return output
532
+ else:
533
+ return channel.makefile_stderr('rb', -1).readlines()
534
+
535
+ @contextmanager
536
+ def cd(self, remotepath=None): # pylint:disable=c0103
537
+ """context manager that can change to a optionally specified remote
538
+ directory and restores the old pwd on exit.
539
+
540
+ :param str|None remotepath: *Default: None* -
541
+ remotepath to temporarily make the current directory
542
+ :returns: None
543
+ :raises: IOError, if remote path doesn't exist
544
+ """
545
+ original_path = self.pwd
546
+ try:
547
+ if remotepath is not None:
548
+ self.cwd(remotepath)
549
+ yield
550
+ finally:
551
+ self.cwd(original_path)
552
+
553
+ def chdir(self, remotepath):
554
+ """change the current working directory on the remote
555
+
556
+ :param str remotepath: the remote path to change to
557
+
558
+ :returns: None
559
+
560
+ :raises: IOError, if path does not exist
561
+
562
+ """
563
+ self._sftp_connect()
564
+ self._sftp.chdir(remotepath)
565
+
566
+ cwd = chdir # synonym for chdir
567
+
568
+ def chmod(self, remotepath, mode=777):
569
+ """set the mode of a remotepath to mode, where mode is an integer
570
+ representation of the octal mode to use.
571
+
572
+ :param str remotepath: the remote path/file to modify
573
+ :param int mode: *Default: 777* -
574
+ int representation of octal mode for directory
575
+
576
+ :returns: None
577
+
578
+ :raises: IOError, if the file doesn't exist
579
+
580
+ """
581
+ self._sftp_connect()
582
+ self._sftp.chmod(remotepath, mode=int(str(mode), 8))
583
+
584
+ def chown(self, remotepath, uid=None, gid=None):
585
+ """ set uid and/or gid on a remotepath, you may specify either or both.
586
+ Unless you have **permission** to do this on the remote server, you
587
+ will raise an IOError: 13 - permission denied
588
+
589
+ :param str remotepath: the remote path/file to modify
590
+ :param int uid: the user id to set on the remotepath
591
+ :param int gid: the group id to set on the remotepath
592
+
593
+ :returns: None
594
+
595
+ :raises:
596
+ IOError, if you don't have permission or the file doesn't exist
597
+
598
+ """
599
+ self._sftp_connect()
600
+ if uid is None or gid is None:
601
+ if uid is None and gid is None: # short circuit if no change
602
+ return
603
+ rstat = self._sftp.stat(remotepath)
604
+ if uid is None:
605
+ uid = rstat.st_uid
606
+ if gid is None:
607
+ gid = rstat.st_gid
608
+
609
+ self._sftp.chown(remotepath, uid=uid, gid=gid)
610
+
611
+ def getcwd(self):
612
+ """return the current working directory on the remote. This is a wrapper
613
+ for paramiko's method and not to be confused with the SFTP command,
614
+ cwd.
615
+
616
+ :returns: (str) the current remote path. None, if not set.
617
+
618
+ """
619
+ self._sftp_connect()
620
+ return self._sftp.getcwd()
621
+
622
+ def listdir(self, remotepath='.'):
623
+ """return a list of files/directories for the given remote path.
624
+ Unlike, paramiko, the directory listing is sorted.
625
+
626
+ :param str remotepath: path to list on the server
627
+
628
+ :returns: (list of str) directory entries, sorted
629
+
630
+ """
631
+ self._sftp_connect()
632
+ return sorted(self._sftp.listdir(remotepath))
633
+
634
+ def listdir_attr(self, remotepath='.'):
635
+ """return a list of SFTPAttribute objects of the files/directories for
636
+ the given remote path. The list is in arbitrary order. It does not
637
+ include the special entries '.' and '..'.
638
+
639
+ The returned SFTPAttributes objects will each have an additional field:
640
+ longname, which may contain a formatted string of the file's
641
+ attributes, in unix format. The content of this string will depend on
642
+ the SFTP server.
643
+
644
+ :param str remotepath: path to list on the server
645
+
646
+ :returns: (list of SFTPAttributes), sorted
647
+
648
+ """
649
+ self._sftp_connect()
650
+ return sorted(self._sftp.listdir_attr(remotepath),
651
+ key=lambda attr: attr.filename)
652
+
653
+ def mkdir(self, remotepath, mode=777):
654
+ """Create a directory named remotepath with mode. On some systems,
655
+ mode is ignored. Where it is used, the current umask value is first
656
+ masked out.
657
+
658
+ :param str remotepath: directory to create`
659
+ :param int mode: *Default: 777* -
660
+ int representation of octal mode for directory
661
+
662
+ :returns: None
663
+
664
+ """
665
+ self._sftp_connect()
666
+ self._sftp.mkdir(remotepath, mode=int(str(mode), 8))
667
+
668
+ def normalize(self, remotepath):
669
+ """Return the expanded path, w.r.t the server, of a given path. This
670
+ can be used to resolve symlinks or determine what the server believes
671
+ to be the :attr:`.pwd`, by passing '.' as remotepath.
672
+
673
+ :param str remotepath: path to be normalized
674
+
675
+ :return: (str) normalized form of the given path
676
+
677
+ :raises: IOError, if remotepath can't be resolved
678
+ """
679
+ self._sftp_connect()
680
+ return self._sftp.normalize(remotepath)
681
+
682
+ def isdir(self, remotepath):
683
+ """return true, if remotepath is a directory
684
+
685
+ :param str remotepath: the path to test
686
+
687
+ :returns: (bool)
688
+
689
+ """
690
+ self._sftp_connect()
691
+ try:
692
+ result = S_ISDIR(self._sftp.stat(remotepath).st_mode)
693
+ except IOError: # no such file
694
+ result = False
695
+ return result
696
+
697
+ def isfile(self, remotepath):
698
+ """return true if remotepath is a file
699
+
700
+ :param str remotepath: the path to test
701
+
702
+ :returns: (bool)
703
+
704
+ """
705
+ self._sftp_connect()
706
+ try:
707
+ result = S_ISREG(self._sftp.stat(remotepath).st_mode)
708
+ except IOError: # no such file
709
+ result = False
710
+ return result
711
+
712
+ def makedirs(self, remotedir, mode=777):
713
+ """create all directories in remotedir as needed, setting their mode
714
+ to mode, if created.
715
+
716
+ If remotedir already exists, silently complete. If a regular file is
717
+ in the way, raise an exception.
718
+
719
+ :param str remotedir: the directory structure to create
720
+ :param int mode: *Default: 777* -
721
+ int representation of octal mode for directory
722
+
723
+ :returns: None
724
+
725
+ :raises: OSError
726
+
727
+ """
728
+ self._sftp_connect()
729
+ if self.isdir(remotedir):
730
+ pass
731
+
732
+ elif self.isfile(remotedir):
733
+ raise OSError("a file with the same name as the remotedir, "
734
+ "'%s', already exists." % remotedir)
735
+ else:
736
+
737
+ head, tail = os.path.split(remotedir)
738
+ if head and not self.isdir(head):
739
+ self.makedirs(head, mode)
740
+
741
+ if tail:
742
+ self.mkdir(remotedir, mode=mode)
743
+
744
+ def readlink(self, remotelink):
745
+ """Return the target of a symlink (shortcut). The result will be
746
+ an absolute pathname.
747
+
748
+ :param str remotelink: remote path of the symlink
749
+
750
+ :return: (str) absolute path to target
751
+
752
+ """
753
+ self._sftp_connect()
754
+ return self._sftp.normalize(self._sftp.readlink(remotelink))
755
+
756
+ def remove(self, remotefile):
757
+ """remove the file @ remotefile, remotefile may include a path, if no
758
+ path, then :attr:`.pwd` is used. This method only works on files
759
+
760
+ :param str remotefile: the remote file to delete
761
+
762
+ :returns: None
763
+
764
+ :raises: IOError
765
+
766
+ """
767
+ self._sftp_connect()
768
+ self._sftp.remove(remotefile)
769
+
770
+ unlink = remove # synonym for remove
771
+
772
+ def rmdir(self, remotepath):
773
+ """remove remote directory
774
+
775
+ :param str remotepath: the remote directory to remove
776
+
777
+ :returns: None
778
+
779
+ """
780
+ self._sftp_connect()
781
+ self._sftp.rmdir(remotepath)
782
+
783
+ def rename(self, remote_src, remote_dest):
784
+ """rename a file or directory on the remote host.
785
+
786
+ :param str remote_src: the remote file/directory to rename
787
+
788
+ :param str remote_dest: the remote file/directory to put it
789
+
790
+ :returns: None
791
+
792
+ :raises: IOError
793
+
794
+ """
795
+ self._sftp_connect()
796
+ self._sftp.rename(remote_src, remote_dest)
797
+
798
+ def stat(self, remotepath):
799
+ """return information about file/directory for the given remote path
800
+
801
+ :param str remotepath: path to stat
802
+
803
+ :returns: (obj) SFTPAttributes
804
+
805
+ """
806
+ self._sftp_connect()
807
+ return self._sftp.stat(remotepath)
808
+
809
+ def lstat(self, remotepath):
810
+ """return information about file/directory for the given remote path,
811
+ without following symbolic links. Otherwise, the same as .stat()
812
+
813
+ :param str remotepath: path to stat
814
+
815
+ :returns: (obj) SFTPAttributes object
816
+
817
+ """
818
+ self._sftp_connect()
819
+ return self._sftp.lstat(remotepath)
820
+
821
+ def close(self):
822
+ """Closes the connection and cleans up."""
823
+ # Close SFTP Connection.
824
+ if self._sftp_live:
825
+ self._sftp.close()
826
+ self._sftp_live = False
827
+ # Close the SSH Transport.
828
+ if self._transport:
829
+ self._transport.close()
830
+ self._transport = None
831
+ # clean up any loggers
832
+ if self._cnopts is not None and self._cnopts.log:
833
+ # if handlers are active they hang around until the app exits
834
+ # this closes and removes the handlers if in use at close
835
+ import logging
836
+ lgr = logging.getLogger("paramiko")
837
+ if lgr:
838
+ lgr.handlers = []
839
+
840
+ def open(self, remote_file, mode='r', bufsize=-1):
841
+ """Open a file on the remote server.
842
+
843
+ See http://paramiko-docs.readthedocs.org/en/latest/api/sftp.html for
844
+ details.
845
+
846
+ :param str remote_file: name of the file to open.
847
+ :param str mode:
848
+ mode (Python-style) to open file (always assumed binary)
849
+ :param int bufsize: *Default: -1* - desired buffering
850
+
851
+ :returns: (obj) SFTPFile, a handle the remote open file
852
+
853
+ :raises: IOError, if the file could not be opened.
854
+
855
+ """
856
+ self._sftp_connect()
857
+ return self._sftp.open(remote_file, mode=mode, bufsize=bufsize)
858
+
859
+ def exists(self, remotepath):
860
+ """Test whether a remotepath exists.
861
+
862
+ :param str remotepath: the remote path to verify
863
+
864
+ :returns: (bool) True, if remotepath exists, else False
865
+
866
+ """
867
+ self._sftp_connect()
868
+ try:
869
+ self._sftp.stat(remotepath)
870
+ except IOError:
871
+ return False
872
+ return True
873
+
874
+ def lexists(self, remotepath):
875
+ """Test whether a remotepath exists. Returns True for broken symbolic
876
+ links
877
+
878
+ :param str remotepath: the remote path to verify
879
+
880
+ :returns: (bool), True, if lexists, else False
881
+
882
+ """
883
+ self._sftp_connect()
884
+ try:
885
+ self._sftp.lstat(remotepath)
886
+ except IOError:
887
+ return False
888
+ return True
889
+
890
+ def symlink(self, remote_src, remote_dest):
891
+ '''create a symlink for a remote file on the server
892
+
893
+ :param str remote_src: path of original file
894
+ :param str remote_dest: path of the created symlink
895
+
896
+ :returns: None
897
+
898
+ :raises:
899
+ any underlying error, IOError if something already exists at
900
+ remote_dest
901
+
902
+ '''
903
+ self._sftp_connect()
904
+ self._sftp.symlink(remote_src, remote_dest)
905
+
906
+ def truncate(self, remotepath, size):
907
+ """Change the size of the file specified by path. Used to modify the
908
+ size of the file, just like the truncate method on Python file objects.
909
+ The new file size is confirmed and returned.
910
+
911
+ :param str remotepath: remote file path to modify
912
+ :param int|long size: the new file size
913
+
914
+ :returns: (int) new size of file
915
+
916
+ :raises: IOError, if file does not exist
917
+
918
+ """
919
+ self._sftp_connect()
920
+ self._sftp.truncate(remotepath, size)
921
+ return self._sftp.stat(remotepath).st_size
922
+
923
+ def walktree(self, remotepath, fcallback, dcallback, ucallback,
924
+ recurse=True):
925
+ '''recursively descend, depth first, the directory tree rooted at
926
+ remotepath, calling discreet callback functions for each regular file,
927
+ directory and unknown file type.
928
+
929
+ :param str remotepath:
930
+ root of remote directory to descend, use '.' to start at
931
+ :attr:`.pwd`
932
+ :param callable fcallback:
933
+ callback function to invoke for a regular file.
934
+ (form: ``func(str)``)
935
+ :param callable dcallback:
936
+ callback function to invoke for a directory. (form: ``func(str)``)
937
+ :param callable ucallback:
938
+ callback function to invoke for an unknown file type.
939
+ (form: ``func(str)``)
940
+ :param bool recurse: *Default: True* - should it recurse
941
+
942
+ :returns: None
943
+
944
+ :raises:
945
+
946
+ '''
947
+ self._sftp_connect()
948
+ for entry in self.listdir(remotepath):
949
+ pathname = posixpath.join(remotepath, entry)
950
+ mode = self._sftp.stat(pathname).st_mode
951
+ if S_ISDIR(mode):
952
+ # It's a directory, call the dcallback function
953
+ dcallback(pathname)
954
+ if recurse:
955
+ # now, recurse into it
956
+ self.walktree(pathname, fcallback, dcallback, ucallback)
957
+ elif S_ISREG(mode):
958
+ # It's a file, call the fcallback function
959
+ fcallback(pathname)
960
+ else:
961
+ # Unknown file type
962
+ ucallback(pathname)
963
+
964
+ @property
965
+ def sftp_client(self):
966
+ """give access to the underlying, connected paramiko SFTPClient object
967
+
968
+ see http://paramiko-docs.readthedocs.org/en/latest/api/sftp.html
969
+
970
+ :params: None
971
+
972
+ :returns: (obj) the active SFTPClient object
973
+
974
+ """
975
+ self._sftp_connect()
976
+ return self._sftp
977
+
978
+ @property
979
+ def active_ciphers(self):
980
+ """Get tuple of currently used local and remote ciphers.
981
+
982
+ :returns:
983
+ (tuple of str) currently used ciphers (local_cipher,
984
+ remote_cipher)
985
+
986
+ """
987
+ return self._transport.local_cipher, self._transport.remote_cipher
988
+
989
+ @property
990
+ def active_compression(self):
991
+ """Get tuple of currently used local and remote compression.
992
+
993
+ :returns:
994
+ (tuple of str) currently used compression (local_compression,
995
+ remote_compression)
996
+
997
+ """
998
+ localc = self._transport.local_compression
999
+ remotec = self._transport.remote_compression
1000
+ return localc, remotec
1001
+
1002
+ @property
1003
+ def security_options(self):
1004
+ """return the available security options recognized by paramiko.
1005
+
1006
+ :returns:
1007
+ (obj) security preferences of the ssh transport. These are tuples
1008
+ of acceptable `.ciphers`, `.digests`, `.key_types`, and key
1009
+ exchange algorithms `.kex`, listed in order of preference.
1010
+
1011
+ """
1012
+
1013
+ return self._transport.get_security_options()
1014
+
1015
+ @property
1016
+ def logfile(self):
1017
+ '''return the name of the file used for logging or False it not logging
1018
+
1019
+ :returns: (str)logfile or (bool) False
1020
+
1021
+ '''
1022
+ return self._cnopts.log
1023
+
1024
+ @property
1025
+ def timeout(self):
1026
+ ''' (float|None) *Default: None* -
1027
+ get or set the underlying socket timeout for pending read/write
1028
+ ops.
1029
+
1030
+ :returns:
1031
+ (float|None) seconds to wait for a pending read/write operation
1032
+ before raising socket.timeout, or None for no timeout
1033
+ '''
1034
+ self._sftp_connect()
1035
+ channel = self._sftp.get_channel()
1036
+
1037
+ return channel.gettimeout()
1038
+
1039
+ @timeout.setter
1040
+ def timeout(self, val):
1041
+ '''setter for timeout'''
1042
+ self._sftp_connect()
1043
+ channel = self._sftp.get_channel()
1044
+ channel.settimeout(val)
1045
+
1046
+ @property
1047
+ def remote_server_key(self):
1048
+ '''return the remote server's key'''
1049
+ return self._transport.get_remote_server_key()
1050
+
1051
+ def __del__(self):
1052
+ """Attempt to clean up if not explicitly closed."""
1053
+ try:
1054
+ self.close()
1055
+ except Exception: # pylint:disable=w0703
1056
+ # never raise from __del__: it would hide the real error
1057
+ pass
1058
+
1059
+ def __enter__(self):
1060
+ return self
1061
+
1062
+ def __exit__(self, etype, value, traceback):
1063
+ self.close()