sftp.py 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180
  1. import datetime
  2. import logging
  3. import os
  4. import types
  5. import uuid
  6. from stat import S_ISDIR, S_ISLNK
  7. import paramiko
  8. from .. import AbstractFileSystem
  9. from ..utils import infer_storage_options
  10. logger = logging.getLogger("fsspec.sftp")
  11. class SFTPFileSystem(AbstractFileSystem):
  12. """Files over SFTP/SSH
  13. Peer-to-peer filesystem over SSH using paramiko.
  14. Note: if using this with the ``open`` or ``open_files``, with full URLs,
  15. there is no way to tell if a path is relative, so all paths are assumed
  16. to be absolute.
  17. """
  18. protocol = "sftp", "ssh"
  19. def __init__(self, host, **ssh_kwargs):
  20. """
  21. Parameters
  22. ----------
  23. host: str
  24. Hostname or IP as a string
  25. temppath: str
  26. Location on the server to put files, when within a transaction
  27. ssh_kwargs: dict
  28. Parameters passed on to connection. See details in
  29. https://docs.paramiko.org/en/3.3/api/client.html#paramiko.client.SSHClient.connect
  30. May include port, username, password...
  31. """
  32. if self._cached:
  33. return
  34. super().__init__(**ssh_kwargs)
  35. self.temppath = ssh_kwargs.pop("temppath", "/tmp") # remote temp directory
  36. self.host = host
  37. self.ssh_kwargs = ssh_kwargs
  38. self._connect()
  39. def _connect(self):
  40. logger.debug("Connecting to SFTP server %s", self.host)
  41. self.client = paramiko.SSHClient()
  42. self.client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
  43. self.client.connect(self.host, **self.ssh_kwargs)
  44. self.ftp = self.client.open_sftp()
  45. @classmethod
  46. def _strip_protocol(cls, path):
  47. return infer_storage_options(path)["path"]
  48. @staticmethod
  49. def _get_kwargs_from_urls(urlpath):
  50. out = infer_storage_options(urlpath)
  51. out.pop("path", None)
  52. out.pop("protocol", None)
  53. return out
  54. def mkdir(self, path, create_parents=True, mode=511):
  55. logger.debug("Creating folder %s", path)
  56. if self.exists(path):
  57. raise FileExistsError(f"File exists: {path}")
  58. if create_parents:
  59. self.makedirs(path)
  60. else:
  61. self.ftp.mkdir(path, mode)
  62. def makedirs(self, path, exist_ok=False, mode=511):
  63. if self.exists(path) and not exist_ok:
  64. raise FileExistsError(f"File exists: {path}")
  65. parts = path.split("/")
  66. new_path = "/" if path[:1] == "/" else ""
  67. for part in parts:
  68. if part:
  69. new_path = f"{new_path}/{part}" if new_path else part
  70. if not self.exists(new_path):
  71. self.ftp.mkdir(new_path, mode)
  72. def rmdir(self, path):
  73. logger.debug("Removing folder %s", path)
  74. self.ftp.rmdir(path)
  75. def info(self, path):
  76. stat = self._decode_stat(self.ftp.stat(path))
  77. stat["name"] = path
  78. return stat
  79. @staticmethod
  80. def _decode_stat(stat, parent_path=None):
  81. if S_ISDIR(stat.st_mode):
  82. t = "directory"
  83. elif S_ISLNK(stat.st_mode):
  84. t = "link"
  85. else:
  86. t = "file"
  87. out = {
  88. "name": "",
  89. "size": stat.st_size,
  90. "type": t,
  91. "uid": stat.st_uid,
  92. "gid": stat.st_gid,
  93. "time": datetime.datetime.fromtimestamp(
  94. stat.st_atime, tz=datetime.timezone.utc
  95. ),
  96. "mtime": datetime.datetime.fromtimestamp(
  97. stat.st_mtime, tz=datetime.timezone.utc
  98. ),
  99. }
  100. if parent_path:
  101. out["name"] = "/".join([parent_path.rstrip("/"), stat.filename])
  102. return out
  103. def ls(self, path, detail=False):
  104. logger.debug("Listing folder %s", path)
  105. stats = [self._decode_stat(stat, path) for stat in self.ftp.listdir_iter(path)]
  106. if detail:
  107. return stats
  108. else:
  109. paths = [stat["name"] for stat in stats]
  110. return sorted(paths)
  111. def put(self, lpath, rpath, callback=None, **kwargs):
  112. logger.debug("Put file %s into %s", lpath, rpath)
  113. self.ftp.put(lpath, rpath)
  114. def get_file(self, rpath, lpath, **kwargs):
  115. if self.isdir(rpath):
  116. os.makedirs(lpath, exist_ok=True)
  117. else:
  118. self.ftp.get(self._strip_protocol(rpath), lpath)
  119. def _open(self, path, mode="rb", block_size=None, **kwargs):
  120. """
  121. block_size: int or None
  122. If 0, no buffering, if 1, line buffering, if >1, buffer that many
  123. bytes, if None use default from paramiko.
  124. """
  125. logger.debug("Opening file %s", path)
  126. if kwargs.get("autocommit", True) is False:
  127. # writes to temporary file, move on commit
  128. path2 = "/".join([self.temppath, str(uuid.uuid4())])
  129. f = self.ftp.open(path2, mode, bufsize=block_size if block_size else -1)
  130. f.temppath = path2
  131. f.targetpath = path
  132. f.fs = self
  133. f.commit = types.MethodType(commit_a_file, f)
  134. f.discard = types.MethodType(discard_a_file, f)
  135. else:
  136. f = self.ftp.open(path, mode, bufsize=block_size if block_size else -1)
  137. return f
  138. def _rm(self, path):
  139. if self.isdir(path):
  140. self.ftp.rmdir(path)
  141. else:
  142. self.ftp.remove(path)
  143. def mv(self, old, new):
  144. logger.debug("Renaming %s into %s", old, new)
  145. self.ftp.posix_rename(old, new)
  146. def commit_a_file(self):
  147. self.fs.mv(self.temppath, self.targetpath)
  148. def discard_a_file(self):
  149. self.fs._rm(self.temppath)