search
HomeBackend DevelopmentPython Tutorial用Python编写一个简单的FUSE文件系统的教程

如果你是我的长期读者,那么你应该知道我在寻找一个完美备份程序,最后我写了一个基于bup的我自己的加密层。

在写encbup的时候,我对仅仅恢复一个文件就必须要下载整个巨大的档案文件的做法不甚满意,但仍然希望能将EncFS和 rdiff-backup一起使用来实现可远程挂载、加密、去重、版本化备份的功能。

再次试用obnam 后(啰嗦一句:它还是慢的出奇),我注意到了它有一个mount命令。深入研究后,我发现了fuse-python和fusepy,感觉用Python写一个FUSE文件系统应该挺简单的。

聪明的读者可能已经意识到了我接下来要做的事情:我决定用Python写一个加密文件系统层!它与EncFS会非常相似,但也有一些重要的区别:

  •     它默认以反向模式运行,接收正常的文件并且暴露一个被加密的目录。任何备份程序会发现(并且备份)这些加密的目录,不需要任何其它的存储。
  •     它也能接受由一个目录列表组成的配置文件,并且在挂载点将这些目录暴露出来。这样的话,所有的备份脚本就需要将挂载点备份,各种不同的目录会立刻得以备份。
  •     它会更偏重于备份,而不是加密存储。写起来应该会挺有意思的。

一个FUSE文件系统示例

写这个脚本的第一步是写出一个纯粹的传递式的文件系统。它仅仅是接受一个目录,并在挂载点将其暴露出来,确保任何在挂载点的修改都会镜像到源数据中。

fusepy 要求你写一个类,里面定义了各种操作系统级别的方法。你可以选择定义那些你的文件系统想要支持的方法,其他的可以暂时不予定义,但是我需要定义全部的方法,因为我的文件系统是一个传递式的文件系统,它应该表现的与原有的文件系统尽可能一致。

写这段代码会非常简单有趣,因为大部分的方法只是对os模块的一些简单封装(确实,你可以直接给它们赋值,比如 open=os.open 等等,但是我的模块需要一些路径扩展)。不幸的是,fuse-python有一个bug(据我所知)是当打开和读文件的时候,它无法将文件句柄回传给文件系统。因而我的脚本不知道某个应用执行读写操作时对应的是哪个文件句柄,从而导致了失败。只需要对fusepy做极少的改动,它就可以很好地运行。它只有一个文件,所以你可以把它直接放到你的工程里。
代码

在这里,我很乐意给出这段代码,当你打算自己实现文件系统的时候可以拿来参考。这段代码提供了一个很好的起点,你可以直接把这个类复制到你的工程中并且根据需要重写里面的一些方法。

接下来是真正的代码了:

#!/usr/bin/env python
 
from __future__ import with_statement
 
import os
import sys
import errno
 
from fuse import FUSE, FuseOSError, Operations
 
class Passthrough(Operations):
  def __init__(self, root):
    self.root = root
 
  # Helpers
  # =======
 
  def _full_path(self, partial):
    if partial.startswith("/"):
      partial = partial[1:]
    path = os.path.join(self.root, partial)
    return path
 
  # Filesystem methods
  # ==================
 
  def access(self, path, mode):
    full_path = self._full_path(path)
    if not os.access(full_path, mode):
      raise FuseOSError(errno.EACCES)
 
  def chmod(self, path, mode):
    full_path = self._full_path(path)
    return os.chmod(full_path, mode)
 
  def chown(self, path, uid, gid):
    full_path = self._full_path(path)
    return os.chown(full_path, uid, gid)
 
  def getattr(self, path, fh=None):
    full_path = self._full_path(path)
    st = os.lstat(full_path)
    return dict((key, getattr(st, key)) for key in ('st_atime', 'st_ctime',
           'st_gid', 'st_mode', 'st_mtime', 'st_nlink', 'st_size', 'st_uid'))
 
  def readdir(self, path, fh):
    full_path = self._full_path(path)
 
    dirents = ['.', '..']
    if os.path.isdir(full_path):
      dirents.extend(os.listdir(full_path))
    for r in dirents:
      yield r
 
  def readlink(self, path):
    pathname = os.readlink(self._full_path(path))
    if pathname.startswith("/"):
      # Path name is absolute, sanitize it.
      return os.path.relpath(pathname, self.root)
    else:
      return pathname
 
  def mknod(self, path, mode, dev):
    return os.mknod(self._full_path(path), mode, dev)
 
  def rmdir(self, path):
    full_path = self._full_path(path)
    return os.rmdir(full_path)
 
  def mkdir(self, path, mode):
    return os.mkdir(self._full_path(path), mode)
 
  def statfs(self, path):
    full_path = self._full_path(path)
    stv = os.statvfs(full_path)
    return dict((key, getattr(stv, key)) for key in ('f_bavail', 'f_bfree',
      'f_blocks', 'f_bsize', 'f_favail', 'f_ffree', 'f_files', 'f_flag',
      'f_frsize', 'f_namemax'))
 
  def unlink(self, path):
    return os.unlink(self._full_path(path))
 
  def symlink(self, target, name):
    return os.symlink(self._full_path(target), self._full_path(name))
 
  def rename(self, old, new):
    return os.rename(self._full_path(old), self._full_path(new))
 
  def link(self, target, name):
    return os.link(self._full_path(target), self._full_path(name))
 
  def utimens(self, path, times=None):
    return os.utime(self._full_path(path), times)
 
  # File methods
  # ============
 
  def open(self, path, flags):
    full_path = self._full_path(path)
    return os.open(full_path, flags)
 
  def create(self, path, mode, fi=None):
    full_path = self._full_path(path)
    return os.open(full_path, os.O_WRONLY | os.O_CREAT, mode)
 
  def read(self, path, length, offset, fh):
    os.lseek(fh, offset, os.SEEK_SET)
    return os.read(fh, length)
 
  def write(self, path, buf, offset, fh):
    os.lseek(fh, offset, os.SEEK_SET)
    return os.write(fh, buf)
 
  def truncate(self, path, length, fh=None):
    full_path = self._full_path(path)
    with open(full_path, 'r+') as f:
      f.truncate(length)
 
  def flush(self, path, fh):
    return os.fsync(fh)
 
  def release(self, path, fh):
    return os.close(fh)
 
  def fsync(self, path, fdatasync, fh):
    return self.flush(path, fh)
 
def main(mountpoint, root):
  FUSE(Passthrough(root), mountpoint, foreground=True)
 
if __name__ == '__main__':
  main(sys.argv[2], sys.argv[1])

如果你想要运行它,只需要安装fusepy,把这段代码放进一个文件(比如myfuse.py)然后运行 python myfuse.py /你的目录 /挂载点目录 。你会发现 “/你的目录” 路径下的所有文件都跑到”/挂载点目录”,还能像用原生文件系统一样操作它们。
结语

总的来说,我并不认为写一个文件系统就这么简单。接下来要做的是在脚本里添加加密/解密的功能,以及一些帮助类的方法。我的目标是能让它除了有更好的扩展性(因为是用Python写的),以及包含一些针对备份文件的额外特性外,可以成为一个EncFS的完全替代品。

如果你想跟进这个脚本的开发过程,请在下面订阅我的邮件列表,或者在Twitter上关注我。一如既往的欢迎反馈(在下面评论就很好)。

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
The 2-Hour Python Plan: A Realistic ApproachThe 2-Hour Python Plan: A Realistic ApproachApr 11, 2025 am 12:04 AM

You can learn basic programming concepts and skills of Python within 2 hours. 1. Learn variables and data types, 2. Master control flow (conditional statements and loops), 3. Understand the definition and use of functions, 4. Quickly get started with Python programming through simple examples and code snippets.

Python: Exploring Its Primary ApplicationsPython: Exploring Its Primary ApplicationsApr 10, 2025 am 09:41 AM

Python is widely used in the fields of web development, data science, machine learning, automation and scripting. 1) In web development, Django and Flask frameworks simplify the development process. 2) In the fields of data science and machine learning, NumPy, Pandas, Scikit-learn and TensorFlow libraries provide strong support. 3) In terms of automation and scripting, Python is suitable for tasks such as automated testing and system management.

How Much Python Can You Learn in 2 Hours?How Much Python Can You Learn in 2 Hours?Apr 09, 2025 pm 04:33 PM

You can learn the basics of Python within two hours. 1. Learn variables and data types, 2. Master control structures such as if statements and loops, 3. Understand the definition and use of functions. These will help you start writing simple Python programs.

How to teach computer novice programming basics in project and problem-driven methods within 10 hours?How to teach computer novice programming basics in project and problem-driven methods within 10 hours?Apr 02, 2025 am 07:18 AM

How to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...

How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading?How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading?Apr 02, 2025 am 07:15 AM

How to avoid being detected when using FiddlerEverywhere for man-in-the-middle readings When you use FiddlerEverywhere...

What should I do if the '__builtin__' module is not found when loading the Pickle file in Python 3.6?What should I do if the '__builtin__' module is not found when loading the Pickle file in Python 3.6?Apr 02, 2025 am 07:12 AM

Error loading Pickle file in Python 3.6 environment: ModuleNotFoundError:Nomodulenamed...

How to improve the accuracy of jieba word segmentation in scenic spot comment analysis?How to improve the accuracy of jieba word segmentation in scenic spot comment analysis?Apr 02, 2025 am 07:09 AM

How to solve the problem of Jieba word segmentation in scenic spot comment analysis? When we are conducting scenic spot comments and analysis, we often use the jieba word segmentation tool to process the text...

How to use regular expression to match the first closed tag and stop?How to use regular expression to match the first closed tag and stop?Apr 02, 2025 am 07:06 AM

How to use regular expression to match the first closed tag and stop? When dealing with HTML or other markup languages, regular expressions are often required to...

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.