跳转到主要内容

SSH 文件系统 -- fsspec 的异步 SSH/SFTP 后端

项目描述

sshfs

sshfs 是使用 fsspec 实现的 SFTP 协议,它通过 asyncssh

特性

  • 通过 SFTP 完整实现 fsspec 协议
  • 支持 SFTP 之外的功能(例如通过 SSH 命令执行的服务器端复制)
  • 相当快(与 paramiko 等替代品相比)
  • 内置通道管理
  • 异步!(感谢 asyncssh

教程

从 PyPI 或 conda-forge 安装 sshfs。这将安装 fsspec 并为 ssh:// URL 注册 sshfs,因此您可以使用以下方式打开文件:

from fsspec import open

with open('ssh://[user@]host[:port]/path/to/file', "w") as file:
    file.write("Hello World!")

with open('ssh://[user@]host[:port]/path/to/file', "r") as file:
    print(file.read())

对于更多操作,您可以直接使用 SSHFileSystem 类。

from sshfs import SSHFileSystem

要使用密码连接,您可以直接指定 username/password 作为关键字参数,然后连接到您选择的任何主机;

# Connect with a password
fs = SSHFileSystem(
    '127.0.0.1',
    username='sam',
    password='fishing'
)

如果您想使用私钥进行认证,您可以传递一个指向密钥路径的字符串,或者提供一个要尝试的密钥列表;

# or with a private key
fs = SSHFileSystem(
    'ssh.example.com',
    client_keys=['/path/to/ssh/key']
)

注意:您还可以将 client_keys 作为参数传递给 fsspec.open

所有操作及其描述都指定在这里:链接。以下是一些示例调用,从允许您检索给定路径元数据的 info() 开始;

>>> details = fs.info('/tmp')
>>> print(f'{details["name"]!r} is a {details["type"]}!')
'/tmp/' is a directory!
>>>
>>> crontab = fs.info('/etc/crontab')
>>> print(f'{crontab["name"]!r} is a {crontab["type"]}!')
'/etc/crontab' is a file!

您还可以通过使用 put_file 放置本地文件或以写入模式打开文件来创建新文件;

>>> with fs.open('/tmp/message.dat', 'wb') as stream:
...     stream.write(b'super secret messsage!')
...

您可以通过 get_file 下载它,或者简单地通过打开它来即时读取它;

>>> with fs.open('/tmp/message.dat') as stream:
...     print(stream.read())
...
b'super secret messsage!'

还有许多其他基本文件系统操作,如 mkdirtouchfind

>>> fs.mkdir('/tmp/dir')
>>> fs.mkdir('/tmp/dir/eggs')
>>> fs.touch('/tmp/dir/spam')
>>> fs.touch('/tmp/dir/eggs/quux')
>>>
>>> for file in fs.find('/tmp/dir'):
...     print(file)
...
/tmp/dir/eggs/quux
/tmp/dir/spam

如果您只想列出目录而不是其子目录,可以使用 ls()

>>> [(detail['name'], detail['type']) for detail in fs.ls('/tmp/dir', detail=True)]
[('/tmp/dir/spam', 'file'), ('/tmp/dir/eggs', 'directory')]

项目详情


下载文件

下载适用于您的平台的文件。如果您不确定该选择哪一个,请了解更多关于 安装包 的信息。

源分发

sshfs-2024.9.0.tar.gz (24.4 kB 查看哈希值)

上传时间:

构建分发

sshfs-2024.9.0-py3-none-any.whl (16.1 kB 查看哈希值)

上传时间: Python 3

支持者