sftp_client.py 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874
  1. # Copyright (C) 2003-2007 Robey Pointer <robeypointer@gmail.com>
  2. #
  3. # This file is part of Paramiko.
  4. #
  5. # Paramiko is free software; you can redistribute it and/or modify it under the
  6. # terms of the GNU Lesser General Public License as published by the Free
  7. # Software Foundation; either version 2.1 of the License, or (at your option)
  8. # any later version.
  9. #
  10. # Paramiko is distributed in the hope that it will be useful, but WITHOUT ANY
  11. # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
  12. # A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
  13. # details.
  14. #
  15. # You should have received a copy of the GNU Lesser General Public License
  16. # along with Paramiko; if not, write to the Free Software Foundation, Inc.,
  17. # 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
  18. from binascii import hexlify
  19. import errno
  20. import os
  21. import stat
  22. import threading
  23. import time
  24. import weakref
  25. from paramiko import util
  26. from paramiko.channel import Channel
  27. from paramiko.message import Message
  28. from paramiko.common import INFO, DEBUG, o777
  29. from paramiko.py3compat import bytestring, b, u, long
  30. from paramiko.sftp import (
  31. BaseSFTP, CMD_OPENDIR, CMD_HANDLE, SFTPError, CMD_READDIR, CMD_NAME,
  32. CMD_CLOSE, SFTP_FLAG_READ, SFTP_FLAG_WRITE, SFTP_FLAG_CREATE,
  33. SFTP_FLAG_TRUNC, SFTP_FLAG_APPEND, SFTP_FLAG_EXCL, CMD_OPEN, CMD_REMOVE,
  34. CMD_RENAME, CMD_MKDIR, CMD_RMDIR, CMD_STAT, CMD_ATTRS, CMD_LSTAT,
  35. CMD_SYMLINK, CMD_SETSTAT, CMD_READLINK, CMD_REALPATH, CMD_STATUS,
  36. CMD_EXTENDED, SFTP_OK, SFTP_EOF, SFTP_NO_SUCH_FILE, SFTP_PERMISSION_DENIED,
  37. )
  38. from paramiko.sftp_attr import SFTPAttributes
  39. from paramiko.ssh_exception import SSHException
  40. from paramiko.sftp_file import SFTPFile
  41. from paramiko.util import ClosingContextManager
  42. def _to_unicode(s):
  43. """
  44. decode a string as ascii or utf8 if possible (as required by the sftp
  45. protocol). if neither works, just return a byte string because the server
  46. probably doesn't know the filename's encoding.
  47. """
  48. try:
  49. return s.encode('ascii')
  50. except (UnicodeError, AttributeError):
  51. try:
  52. return s.decode('utf-8')
  53. except UnicodeError:
  54. return s
  55. b_slash = b'/'
  56. class SFTPClient(BaseSFTP, ClosingContextManager):
  57. """
  58. SFTP client object.
  59. Used to open an SFTP session across an open SSH `.Transport` and perform
  60. remote file operations.
  61. Instances of this class may be used as context managers.
  62. """
  63. def __init__(self, sock):
  64. """
  65. Create an SFTP client from an existing `.Channel`. The channel
  66. should already have requested the ``"sftp"`` subsystem.
  67. An alternate way to create an SFTP client context is by using
  68. `from_transport`.
  69. :param .Channel sock: an open `.Channel` using the ``"sftp"`` subsystem
  70. :raises:
  71. `.SSHException` -- if there's an exception while negotiating sftp
  72. """
  73. BaseSFTP.__init__(self)
  74. self.sock = sock
  75. self.ultra_debug = False
  76. self.request_number = 1
  77. # lock for request_number
  78. self._lock = threading.Lock()
  79. self._cwd = None
  80. # request # -> SFTPFile
  81. self._expecting = weakref.WeakValueDictionary()
  82. if type(sock) is Channel:
  83. # override default logger
  84. transport = self.sock.get_transport()
  85. self.logger = util.get_logger(
  86. transport.get_log_channel() + '.sftp')
  87. self.ultra_debug = transport.get_hexdump()
  88. try:
  89. server_version = self._send_version()
  90. except EOFError:
  91. raise SSHException('EOF during negotiation')
  92. self._log(
  93. INFO,
  94. 'Opened sftp connection (server version %d)' % server_version)
  95. @classmethod
  96. def from_transport(cls, t, window_size=None, max_packet_size=None):
  97. """
  98. Create an SFTP client channel from an open `.Transport`.
  99. Setting the window and packet sizes might affect the transfer speed.
  100. The default settings in the `.Transport` class are the same as in
  101. OpenSSH and should work adequately for both files transfers and
  102. interactive sessions.
  103. :param .Transport t: an open `.Transport` which is already
  104. authenticated
  105. :param int window_size:
  106. optional window size for the `.SFTPClient` session.
  107. :param int max_packet_size:
  108. optional max packet size for the `.SFTPClient` session..
  109. :return:
  110. a new `.SFTPClient` object, referring to an sftp session (channel)
  111. across the transport
  112. .. versionchanged:: 1.15
  113. Added the ``window_size`` and ``max_packet_size`` arguments.
  114. """
  115. chan = t.open_session(window_size=window_size,
  116. max_packet_size=max_packet_size)
  117. if chan is None:
  118. return None
  119. chan.invoke_subsystem('sftp')
  120. return cls(chan)
  121. def _log(self, level, msg, *args):
  122. if isinstance(msg, list):
  123. for m in msg:
  124. self._log(level, m, *args)
  125. else:
  126. # escape '%' in msg (they could come from file or directory names)
  127. # before logging
  128. msg = msg.replace('%', '%%')
  129. super(SFTPClient, self)._log(
  130. level,
  131. "[chan %s] " + msg, *([self.sock.get_name()] + list(args)))
  132. def close(self):
  133. """
  134. Close the SFTP session and its underlying channel.
  135. .. versionadded:: 1.4
  136. """
  137. self._log(INFO, 'sftp session closed.')
  138. self.sock.close()
  139. def get_channel(self):
  140. """
  141. Return the underlying `.Channel` object for this SFTP session. This
  142. might be useful for doing things like setting a timeout on the channel.
  143. .. versionadded:: 1.7.1
  144. """
  145. return self.sock
  146. def listdir(self, path='.'):
  147. """
  148. Return a list containing the names of the entries in the given
  149. ``path``.
  150. The list is in arbitrary order. It does not include the special
  151. entries ``'.'`` and ``'..'`` even if they are present in the folder.
  152. This method is meant to mirror ``os.listdir`` as closely as possible.
  153. For a list of full `.SFTPAttributes` objects, see `listdir_attr`.
  154. :param str path: path to list (defaults to ``'.'``)
  155. """
  156. return [f.filename for f in self.listdir_attr(path)]
  157. def listdir_attr(self, path='.'):
  158. """
  159. Return a list containing `.SFTPAttributes` objects corresponding to
  160. files in the given ``path``. The list is in arbitrary order. It does
  161. not include the special entries ``'.'`` and ``'..'`` even if they are
  162. present in the folder.
  163. The returned `.SFTPAttributes` objects will each have an additional
  164. field: ``longname``, which may contain a formatted string of the file's
  165. attributes, in unix format. The content of this string will probably
  166. depend on the SFTP server implementation.
  167. :param str path: path to list (defaults to ``'.'``)
  168. :return: list of `.SFTPAttributes` objects
  169. .. versionadded:: 1.2
  170. """
  171. path = self._adjust_cwd(path)
  172. self._log(DEBUG, 'listdir(%r)' % path)
  173. t, msg = self._request(CMD_OPENDIR, path)
  174. if t != CMD_HANDLE:
  175. raise SFTPError('Expected handle')
  176. handle = msg.get_binary()
  177. filelist = []
  178. while True:
  179. try:
  180. t, msg = self._request(CMD_READDIR, handle)
  181. except EOFError:
  182. # done with handle
  183. break
  184. if t != CMD_NAME:
  185. raise SFTPError('Expected name response')
  186. count = msg.get_int()
  187. for i in range(count):
  188. filename = msg.get_text()
  189. longname = msg.get_text()
  190. attr = SFTPAttributes._from_msg(msg, filename, longname)
  191. if (filename != '.') and (filename != '..'):
  192. filelist.append(attr)
  193. self._request(CMD_CLOSE, handle)
  194. return filelist
  195. def listdir_iter(self, path='.', read_aheads=50):
  196. """
  197. Generator version of `.listdir_attr`.
  198. See the API docs for `.listdir_attr` for overall details.
  199. This function adds one more kwarg on top of `.listdir_attr`:
  200. ``read_aheads``, an integer controlling how many
  201. ``SSH_FXP_READDIR`` requests are made to the server. The default of 50
  202. should suffice for most file listings as each request/response cycle
  203. may contain multiple files (dependent on server implementation.)
  204. .. versionadded:: 1.15
  205. """
  206. path = self._adjust_cwd(path)
  207. self._log(DEBUG, 'listdir(%r)' % path)
  208. t, msg = self._request(CMD_OPENDIR, path)
  209. if t != CMD_HANDLE:
  210. raise SFTPError('Expected handle')
  211. handle = msg.get_string()
  212. nums = list()
  213. while True:
  214. try:
  215. # Send out a bunch of readdir requests so that we can read the
  216. # responses later on Section 6.7 of the SSH file transfer RFC
  217. # explains this
  218. # http://filezilla-project.org/specs/draft-ietf-secsh-filexfer-02.txt
  219. for i in range(read_aheads):
  220. num = self._async_request(type(None), CMD_READDIR, handle)
  221. nums.append(num)
  222. # For each of our sent requests
  223. # Read and parse the corresponding packets
  224. # If we're at the end of our queued requests, then fire off
  225. # some more requests
  226. # Exit the loop when we've reached the end of the directory
  227. # handle
  228. for num in nums:
  229. t, pkt_data = self._read_packet()
  230. msg = Message(pkt_data)
  231. new_num = msg.get_int()
  232. if num == new_num:
  233. if t == CMD_STATUS:
  234. self._convert_status(msg)
  235. count = msg.get_int()
  236. for i in range(count):
  237. filename = msg.get_text()
  238. longname = msg.get_text()
  239. attr = SFTPAttributes._from_msg(
  240. msg, filename, longname)
  241. if (filename != '.') and (filename != '..'):
  242. yield attr
  243. # If we've hit the end of our queued requests, reset nums.
  244. nums = list()
  245. except EOFError:
  246. self._request(CMD_CLOSE, handle)
  247. return
  248. def open(self, filename, mode='r', bufsize=-1):
  249. """
  250. Open a file on the remote server. The arguments are the same as for
  251. Python's built-in `python:file` (aka `python:open`). A file-like
  252. object is returned, which closely mimics the behavior of a normal
  253. Python file object, including the ability to be used as a context
  254. manager.
  255. The mode indicates how the file is to be opened: ``'r'`` for reading,
  256. ``'w'`` for writing (truncating an existing file), ``'a'`` for
  257. appending, ``'r+'`` for reading/writing, ``'w+'`` for reading/writing
  258. (truncating an existing file), ``'a+'`` for reading/appending. The
  259. Python ``'b'`` flag is ignored, since SSH treats all files as binary.
  260. The ``'U'`` flag is supported in a compatible way.
  261. Since 1.5.2, an ``'x'`` flag indicates that the operation should only
  262. succeed if the file was created and did not previously exist. This has
  263. no direct mapping to Python's file flags, but is commonly known as the
  264. ``O_EXCL`` flag in posix.
  265. The file will be buffered in standard Python style by default, but
  266. can be altered with the ``bufsize`` parameter. ``0`` turns off
  267. buffering, ``1`` uses line buffering, and any number greater than 1
  268. (``>1``) uses that specific buffer size.
  269. :param str filename: name of the file to open
  270. :param str mode: mode (Python-style) to open in
  271. :param int bufsize: desired buffering (-1 = default buffer size)
  272. :return: an `.SFTPFile` object representing the open file
  273. :raises: ``IOError`` -- if the file could not be opened.
  274. """
  275. filename = self._adjust_cwd(filename)
  276. self._log(DEBUG, 'open(%r, %r)' % (filename, mode))
  277. imode = 0
  278. if ('r' in mode) or ('+' in mode):
  279. imode |= SFTP_FLAG_READ
  280. if ('w' in mode) or ('+' in mode) or ('a' in mode):
  281. imode |= SFTP_FLAG_WRITE
  282. if 'w' in mode:
  283. imode |= SFTP_FLAG_CREATE | SFTP_FLAG_TRUNC
  284. if 'a' in mode:
  285. imode |= SFTP_FLAG_CREATE | SFTP_FLAG_APPEND
  286. if 'x' in mode:
  287. imode |= SFTP_FLAG_CREATE | SFTP_FLAG_EXCL
  288. attrblock = SFTPAttributes()
  289. t, msg = self._request(CMD_OPEN, filename, imode, attrblock)
  290. if t != CMD_HANDLE:
  291. raise SFTPError('Expected handle')
  292. handle = msg.get_binary()
  293. self._log(
  294. DEBUG,
  295. 'open(%r, %r) -> %s' % (filename, mode, hexlify(handle)))
  296. return SFTPFile(self, handle, mode, bufsize)
  297. # Python continues to vacillate about "open" vs "file"...
  298. file = open
  299. def remove(self, path):
  300. """
  301. Remove the file at the given path. This only works on files; for
  302. removing folders (directories), use `rmdir`.
  303. :param str path: path (absolute or relative) of the file to remove
  304. :raises: ``IOError`` -- if the path refers to a folder (directory)
  305. """
  306. path = self._adjust_cwd(path)
  307. self._log(DEBUG, 'remove(%r)' % path)
  308. self._request(CMD_REMOVE, path)
  309. unlink = remove
  310. def rename(self, oldpath, newpath):
  311. """
  312. Rename a file or folder from ``oldpath`` to ``newpath``.
  313. :param str oldpath:
  314. existing name of the file or folder
  315. :param str newpath:
  316. new name for the file or folder, must not exist already
  317. :raises:
  318. ``IOError`` -- if ``newpath`` is a folder, or something else goes
  319. wrong
  320. """
  321. oldpath = self._adjust_cwd(oldpath)
  322. newpath = self._adjust_cwd(newpath)
  323. self._log(DEBUG, 'rename(%r, %r)' % (oldpath, newpath))
  324. self._request(CMD_RENAME, oldpath, newpath)
  325. def posix_rename(self, oldpath, newpath):
  326. """
  327. Rename a file or folder from ``oldpath`` to ``newpath``, following
  328. posix conventions.
  329. :param str oldpath: existing name of the file or folder
  330. :param str newpath: new name for the file or folder, will be
  331. overwritten if it already exists
  332. :raises:
  333. ``IOError`` -- if ``newpath`` is a folder, posix-rename is not
  334. supported by the server or something else goes wrong
  335. """
  336. oldpath = self._adjust_cwd(oldpath)
  337. newpath = self._adjust_cwd(newpath)
  338. self._log(DEBUG, 'posix_rename(%r, %r)' % (oldpath, newpath))
  339. self._request(
  340. CMD_EXTENDED, "posix-rename@openssh.com", oldpath, newpath
  341. )
  342. def mkdir(self, path, mode=o777):
  343. """
  344. Create a folder (directory) named ``path`` with numeric mode ``mode``.
  345. The default mode is 0777 (octal). On some systems, mode is ignored.
  346. Where it is used, the current umask value is first masked out.
  347. :param str path: name of the folder to create
  348. :param int mode: permissions (posix-style) for the newly-created folder
  349. """
  350. path = self._adjust_cwd(path)
  351. self._log(DEBUG, 'mkdir(%r, %r)' % (path, mode))
  352. attr = SFTPAttributes()
  353. attr.st_mode = mode
  354. self._request(CMD_MKDIR, path, attr)
  355. def rmdir(self, path):
  356. """
  357. Remove the folder named ``path``.
  358. :param str path: name of the folder to remove
  359. """
  360. path = self._adjust_cwd(path)
  361. self._log(DEBUG, 'rmdir(%r)' % path)
  362. self._request(CMD_RMDIR, path)
  363. def stat(self, path):
  364. """
  365. Retrieve information about a file on the remote system. The return
  366. value is an object whose attributes correspond to the attributes of
  367. Python's ``stat`` structure as returned by ``os.stat``, except that it
  368. contains fewer fields. An SFTP server may return as much or as little
  369. info as it wants, so the results may vary from server to server.
  370. Unlike a Python `python:stat` object, the result may not be accessed as
  371. a tuple. This is mostly due to the author's slack factor.
  372. The fields supported are: ``st_mode``, ``st_size``, ``st_uid``,
  373. ``st_gid``, ``st_atime``, and ``st_mtime``.
  374. :param str path: the filename to stat
  375. :return:
  376. an `.SFTPAttributes` object containing attributes about the given
  377. file
  378. """
  379. path = self._adjust_cwd(path)
  380. self._log(DEBUG, 'stat(%r)' % path)
  381. t, msg = self._request(CMD_STAT, path)
  382. if t != CMD_ATTRS:
  383. raise SFTPError('Expected attributes')
  384. return SFTPAttributes._from_msg(msg)
  385. def lstat(self, path):
  386. """
  387. Retrieve information about a file on the remote system, without
  388. following symbolic links (shortcuts). This otherwise behaves exactly
  389. the same as `stat`.
  390. :param str path: the filename to stat
  391. :return:
  392. an `.SFTPAttributes` object containing attributes about the given
  393. file
  394. """
  395. path = self._adjust_cwd(path)
  396. self._log(DEBUG, 'lstat(%r)' % path)
  397. t, msg = self._request(CMD_LSTAT, path)
  398. if t != CMD_ATTRS:
  399. raise SFTPError('Expected attributes')
  400. return SFTPAttributes._from_msg(msg)
  401. def symlink(self, source, dest):
  402. """
  403. Create a symbolic link to the ``source`` path at ``destination``.
  404. :param str source: path of the original file
  405. :param str dest: path of the newly created symlink
  406. """
  407. dest = self._adjust_cwd(dest)
  408. self._log(DEBUG, 'symlink(%r, %r)' % (source, dest))
  409. source = bytestring(source)
  410. self._request(CMD_SYMLINK, source, dest)
  411. def chmod(self, path, mode):
  412. """
  413. Change the mode (permissions) of a file. The permissions are
  414. unix-style and identical to those used by Python's `os.chmod`
  415. function.
  416. :param str path: path of the file to change the permissions of
  417. :param int mode: new permissions
  418. """
  419. path = self._adjust_cwd(path)
  420. self._log(DEBUG, 'chmod(%r, %r)' % (path, mode))
  421. attr = SFTPAttributes()
  422. attr.st_mode = mode
  423. self._request(CMD_SETSTAT, path, attr)
  424. def chown(self, path, uid, gid):
  425. """
  426. Change the owner (``uid``) and group (``gid``) of a file. As with
  427. Python's `os.chown` function, you must pass both arguments, so if you
  428. only want to change one, use `stat` first to retrieve the current
  429. owner and group.
  430. :param str path: path of the file to change the owner and group of
  431. :param int uid: new owner's uid
  432. :param int gid: new group id
  433. """
  434. path = self._adjust_cwd(path)
  435. self._log(DEBUG, 'chown(%r, %r, %r)' % (path, uid, gid))
  436. attr = SFTPAttributes()
  437. attr.st_uid, attr.st_gid = uid, gid
  438. self._request(CMD_SETSTAT, path, attr)
  439. def utime(self, path, times):
  440. """
  441. Set the access and modified times of the file specified by ``path``.
  442. If ``times`` is ``None``, then the file's access and modified times
  443. are set to the current time. Otherwise, ``times`` must be a 2-tuple
  444. of numbers, of the form ``(atime, mtime)``, which is used to set the
  445. access and modified times, respectively. This bizarre API is mimicked
  446. from Python for the sake of consistency -- I apologize.
  447. :param str path: path of the file to modify
  448. :param tuple times:
  449. ``None`` or a tuple of (access time, modified time) in standard
  450. internet epoch time (seconds since 01 January 1970 GMT)
  451. """
  452. path = self._adjust_cwd(path)
  453. if times is None:
  454. times = (time.time(), time.time())
  455. self._log(DEBUG, 'utime(%r, %r)' % (path, times))
  456. attr = SFTPAttributes()
  457. attr.st_atime, attr.st_mtime = times
  458. self._request(CMD_SETSTAT, path, attr)
  459. def truncate(self, path, size):
  460. """
  461. Change the size of the file specified by ``path``. This usually
  462. extends or shrinks the size of the file, just like the `~file.truncate`
  463. method on Python file objects.
  464. :param str path: path of the file to modify
  465. :param int size: the new size of the file
  466. """
  467. path = self._adjust_cwd(path)
  468. self._log(DEBUG, 'truncate(%r, %r)' % (path, size))
  469. attr = SFTPAttributes()
  470. attr.st_size = size
  471. self._request(CMD_SETSTAT, path, attr)
  472. def readlink(self, path):
  473. """
  474. Return the target of a symbolic link (shortcut). You can use
  475. `symlink` to create these. The result may be either an absolute or
  476. relative pathname.
  477. :param str path: path of the symbolic link file
  478. :return: target path, as a `str`
  479. """
  480. path = self._adjust_cwd(path)
  481. self._log(DEBUG, 'readlink(%r)' % path)
  482. t, msg = self._request(CMD_READLINK, path)
  483. if t != CMD_NAME:
  484. raise SFTPError('Expected name response')
  485. count = msg.get_int()
  486. if count == 0:
  487. return None
  488. if count != 1:
  489. raise SFTPError('Readlink returned %d results' % count)
  490. return _to_unicode(msg.get_string())
  491. def normalize(self, path):
  492. """
  493. Return the normalized path (on the server) of a given path. This
  494. can be used to quickly resolve symbolic links or determine what the
  495. server is considering to be the "current folder" (by passing ``'.'``
  496. as ``path``).
  497. :param str path: path to be normalized
  498. :return: normalized form of the given path (as a `str`)
  499. :raises: ``IOError`` -- if the path can't be resolved on the server
  500. """
  501. path = self._adjust_cwd(path)
  502. self._log(DEBUG, 'normalize(%r)' % path)
  503. t, msg = self._request(CMD_REALPATH, path)
  504. if t != CMD_NAME:
  505. raise SFTPError('Expected name response')
  506. count = msg.get_int()
  507. if count != 1:
  508. raise SFTPError('Realpath returned %d results' % count)
  509. return msg.get_text()
  510. def chdir(self, path=None):
  511. """
  512. Change the "current directory" of this SFTP session. Since SFTP
  513. doesn't really have the concept of a current working directory, this is
  514. emulated by Paramiko. Once you use this method to set a working
  515. directory, all operations on this `.SFTPClient` object will be relative
  516. to that path. You can pass in ``None`` to stop using a current working
  517. directory.
  518. :param str path: new current working directory
  519. :raises:
  520. ``IOError`` -- if the requested path doesn't exist on the server
  521. .. versionadded:: 1.4
  522. """
  523. if path is None:
  524. self._cwd = None
  525. return
  526. if not stat.S_ISDIR(self.stat(path).st_mode):
  527. raise SFTPError(
  528. errno.ENOTDIR, "%s: %s" % (os.strerror(errno.ENOTDIR), path))
  529. self._cwd = b(self.normalize(path))
  530. def getcwd(self):
  531. """
  532. Return the "current working directory" for this SFTP session, as
  533. emulated by Paramiko. If no directory has been set with `chdir`,
  534. this method will return ``None``.
  535. .. versionadded:: 1.4
  536. """
  537. # TODO: make class initialize with self._cwd set to self.normalize('.')
  538. return self._cwd and u(self._cwd)
  539. def _transfer_with_callback(self, reader, writer, file_size, callback):
  540. size = 0
  541. while True:
  542. data = reader.read(32768)
  543. writer.write(data)
  544. size += len(data)
  545. if len(data) == 0:
  546. break
  547. if callback is not None:
  548. callback(size, file_size)
  549. return size
  550. def putfo(self, fl, remotepath, file_size=0, callback=None, confirm=True):
  551. """
  552. Copy the contents of an open file object (``fl``) to the SFTP server as
  553. ``remotepath``. Any exception raised by operations will be passed
  554. through.
  555. The SFTP operations use pipelining for speed.
  556. :param fl: opened file or file-like object to copy
  557. :param str remotepath: the destination path on the SFTP server
  558. :param int file_size:
  559. optional size parameter passed to callback. If none is specified,
  560. size defaults to 0
  561. :param callable callback:
  562. optional callback function (form: ``func(int, int)``) that accepts
  563. the bytes transferred so far and the total bytes to be transferred
  564. (since 1.7.4)
  565. :param bool confirm:
  566. whether to do a stat() on the file afterwards to confirm the file
  567. size (since 1.7.7)
  568. :return:
  569. an `.SFTPAttributes` object containing attributes about the given
  570. file.
  571. .. versionadded:: 1.10
  572. """
  573. with self.file(remotepath, 'wb') as fr:
  574. fr.set_pipelined(True)
  575. size = self._transfer_with_callback(
  576. reader=fl, writer=fr, file_size=file_size, callback=callback
  577. )
  578. if confirm:
  579. s = self.stat(remotepath)
  580. if s.st_size != size:
  581. raise IOError(
  582. 'size mismatch in put! %d != %d' % (s.st_size, size))
  583. else:
  584. s = SFTPAttributes()
  585. return s
  586. def put(self, localpath, remotepath, callback=None, confirm=True):
  587. """
  588. Copy a local file (``localpath``) to the SFTP server as ``remotepath``.
  589. Any exception raised by operations will be passed through. This
  590. method is primarily provided as a convenience.
  591. The SFTP operations use pipelining for speed.
  592. :param str localpath: the local file to copy
  593. :param str remotepath: the destination path on the SFTP server. Note
  594. that the filename should be included. Only specifying a directory
  595. may result in an error.
  596. :param callable callback:
  597. optional callback function (form: ``func(int, int)``) that accepts
  598. the bytes transferred so far and the total bytes to be transferred
  599. :param bool confirm:
  600. whether to do a stat() on the file afterwards to confirm the file
  601. size
  602. :return: an `.SFTPAttributes` object containing attributes about the
  603. given file
  604. .. versionadded:: 1.4
  605. .. versionchanged:: 1.7.4
  606. ``callback`` and rich attribute return value added.
  607. .. versionchanged:: 1.7.7
  608. ``confirm`` param added.
  609. """
  610. file_size = os.stat(localpath).st_size
  611. with open(localpath, 'rb') as fl:
  612. return self.putfo(fl, remotepath, file_size, callback, confirm)
  613. def getfo(self, remotepath, fl, callback=None):
  614. """
  615. Copy a remote file (``remotepath``) from the SFTP server and write to
  616. an open file or file-like object, ``fl``. Any exception raised by
  617. operations will be passed through. This method is primarily provided
  618. as a convenience.
  619. :param object remotepath: opened file or file-like object to copy to
  620. :param str fl:
  621. the destination path on the local host or open file object
  622. :param callable callback:
  623. optional callback function (form: ``func(int, int)``) that accepts
  624. the bytes transferred so far and the total bytes to be transferred
  625. :return: the `number <int>` of bytes written to the opened file object
  626. .. versionadded:: 1.10
  627. """
  628. file_size = self.stat(remotepath).st_size
  629. with self.open(remotepath, 'rb') as fr:
  630. fr.prefetch(file_size)
  631. return self._transfer_with_callback(
  632. reader=fr, writer=fl, file_size=file_size, callback=callback
  633. )
  634. def get(self, remotepath, localpath, callback=None):
  635. """
  636. Copy a remote file (``remotepath``) from the SFTP server to the local
  637. host as ``localpath``. Any exception raised by operations will be
  638. passed through. This method is primarily provided as a convenience.
  639. :param str remotepath: the remote file to copy
  640. :param str localpath: the destination path on the local host
  641. :param callable callback:
  642. optional callback function (form: ``func(int, int)``) that accepts
  643. the bytes transferred so far and the total bytes to be transferred
  644. .. versionadded:: 1.4
  645. .. versionchanged:: 1.7.4
  646. Added the ``callback`` param
  647. """
  648. with open(localpath, 'wb') as fl:
  649. size = self.getfo(remotepath, fl, callback)
  650. s = os.stat(localpath)
  651. if s.st_size != size:
  652. raise IOError(
  653. 'size mismatch in get! %d != %d' % (s.st_size, size))
  654. # ...internals...
  655. def _request(self, t, *arg):
  656. num = self._async_request(type(None), t, *arg)
  657. return self._read_response(num)
  658. def _async_request(self, fileobj, t, *arg):
  659. # this method may be called from other threads (prefetch)
  660. self._lock.acquire()
  661. try:
  662. msg = Message()
  663. msg.add_int(self.request_number)
  664. for item in arg:
  665. if isinstance(item, long):
  666. msg.add_int64(item)
  667. elif isinstance(item, int):
  668. msg.add_int(item)
  669. elif isinstance(item, SFTPAttributes):
  670. item._pack(msg)
  671. else:
  672. # For all other types, rely on as_string() to either coerce
  673. # to bytes before writing or raise a suitable exception.
  674. msg.add_string(item)
  675. num = self.request_number
  676. self._expecting[num] = fileobj
  677. self.request_number += 1
  678. finally:
  679. self._lock.release()
  680. self._send_packet(t, msg)
  681. return num
  682. def _read_response(self, waitfor=None):
  683. while True:
  684. try:
  685. t, data = self._read_packet()
  686. except EOFError as e:
  687. raise SSHException('Server connection dropped: %s' % str(e))
  688. msg = Message(data)
  689. num = msg.get_int()
  690. self._lock.acquire()
  691. try:
  692. if num not in self._expecting:
  693. # might be response for a file that was closed before
  694. # responses came back
  695. self._log(DEBUG, 'Unexpected response #%d' % (num,))
  696. if waitfor is None:
  697. # just doing a single check
  698. break
  699. continue
  700. fileobj = self._expecting[num]
  701. del self._expecting[num]
  702. finally:
  703. self._lock.release()
  704. if num == waitfor:
  705. # synchronous
  706. if t == CMD_STATUS:
  707. self._convert_status(msg)
  708. return t, msg
  709. # can not rewrite this to deal with E721, either as a None check
  710. # nor as not an instance of None or NoneType
  711. if fileobj is not type(None): # noqa
  712. fileobj._async_response(t, msg, num)
  713. if waitfor is None:
  714. # just doing a single check
  715. break
  716. return None, None
  717. def _finish_responses(self, fileobj):
  718. while fileobj in self._expecting.values():
  719. self._read_response()
  720. fileobj._check_exception()
  721. def _convert_status(self, msg):
  722. """
  723. Raises EOFError or IOError on error status; otherwise does nothing.
  724. """
  725. code = msg.get_int()
  726. text = msg.get_text()
  727. if code == SFTP_OK:
  728. return
  729. elif code == SFTP_EOF:
  730. raise EOFError(text)
  731. elif code == SFTP_NO_SUCH_FILE:
  732. # clever idea from john a. meinel: map the error codes to errno
  733. raise IOError(errno.ENOENT, text)
  734. elif code == SFTP_PERMISSION_DENIED:
  735. raise IOError(errno.EACCES, text)
  736. else:
  737. raise IOError(text)
  738. def _adjust_cwd(self, path):
  739. """
  740. Return an adjusted path if we're emulating a "current working
  741. directory" for the server.
  742. """
  743. path = b(path)
  744. if self._cwd is None:
  745. return path
  746. if len(path) and path[0:1] == b_slash:
  747. # absolute path
  748. return path
  749. if self._cwd == b_slash:
  750. return self._cwd + path
  751. return self._cwd + b_slash + path
  752. class SFTP(SFTPClient):
  753. """
  754. An alias for `.SFTPClient` for backwards compatibility.
  755. """
  756. pass