sftp_client.py 34 KB

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