繁体   English   中英

如何使用 Python 挂载文件系统?

[英]How do I mount a filesystem using Python?

我确定这是一个简单的问题,我的 Google-fu 显然让我失望。

如何使用 Python 挂载文件系统,相当于运行 shell 命令mount ...

显然我可以使用os.system来运行 shell 命令,但肯定有一个很好的整洁的 Python 接口来安装系统调用。

我找不到。 我认为这只是一个不错的、简单的os.mount()

正如其他人指出的那样,没有内置的mount功能。 但是,使用ctypes很容易创建一个,这比使用 shell 命令更轻,更可靠。

下面是一个例子:

import ctypes
import ctypes.util
import os

libc = ctypes.CDLL(ctypes.util.find_library('c'), use_errno=True)
libc.mount.argtypes = (ctypes.c_char_p, ctypes.c_char_p, ctypes.c_char_p, ctypes.c_ulong, ctypes.c_char_p)

def mount(source, target, fs, options=''):
  ret = libc.mount(source.encode(), target.encode(), fs.encode(), 0, options.encode())
  if ret < 0:
    errno = ctypes.get_errno()
    raise OSError(errno, f"Error mounting {source} ({fs}) on {target} with options '{options}': {os.strerror(errno)}")

mount('/dev/sdb1', '/mnt', 'ext4', 'rw')

另一种选择是使用相当新的sh模块。 根据其文档,它提供了与 Python 中的 Shell 命令的流畅集成。

我现在正在尝试它,它看起来很有希望。

from sh import mount

mount("/dev/", "/mnt/test", "-t ext4")

另请看一下bake ,它允许您快速抽象出新函数中的命令。

您可以在util-linux项目中为libmount使用 Python 绑定:

import pylibmount as mnt

cxt = mnt.Context()
cxt.source = '/dev/sda1'
cxt.target = '/mnt/'
cxt.mount()

有关详细信息,请参阅此示例

ctypes导入cdll 然后加载你的 os libc ,然后使用libc.mount()

阅读libc的文档以获取挂载参数

挂载是一种非常罕见的操作,因此是否有任何直接的 Python 方法可以做到这一点值得怀疑。

无论是使用ctypes直接从蟒蛇做了手术,否则(可能更好),使用subprocess调用mount命令(不使用os.system() -好得多使用subprocess )。

正如其他人所说,直接访问系统调用对您没有帮助,除非您以 root 身份运行(出于多种原因,这通常很糟糕)。 因此,最好调用“挂载”程序,并希望/etc/fstab为用户启用挂载。

调用mount的最佳方法是使用以下命令:

subprocess.check_call(["mount", what])

哪里what或者是设备路径,或者挂载点的路径。 如果出现任何问题,则会引发异常。

check_call比一个更简单的界面Popen和其低级别的兄弟)

请注意,调用您的 libc 挂载函数将需要 root 权限; Popen(['mount'...) 仅当特定的挂载在 fstab 中没有被祝福时才会生效(执行这些检查的是挂载可执行文件 setuid root)。

我知道这是旧的,但我有一个类似的问题,pexpect 解决了它。 我可以使用 mount 命令挂载我的 Windows 共享驱动器,但我无法传递我的密码,因为它必须被转义。 我厌倦了逃避它并尝试使用也会导致问题的凭据文件。 这似乎对我有用。

password = "$wirleysaysneverquit!!!"

cmd = "sudo mount -t cifs -o username=myusername,domain=CORPORATE,rw,hard,nosetuids,noperm,sec=ntlm //mylong.evenlonger.shareddrivecompany.com/some/folder /mnt/folder -v"
p = pexpect.spawn( cmd )
p.expect( ": " )
print( p.before + p.after + password )
p.sendline( password )
p.expect( "\r\n" )

output = p.read()
arroutput = output.split("\r\n")
for o in arroutput:
    print( o )

来源: https : //gist.github.com/nitrocode/192d5667ce9da67c8eac

糟糕的是,挂载和卸载属于高度依赖系统的事情,因为它们是

  • 很少使用和
  • 会影响系统稳定性

没有可移植的解决方案。 从那以后,我同意 Ferdinand Beyer 的观点,即不太可能存在通用的 Python 解决方案。

这肯定是一个很好的整洁的 python 接口挂载系统调用。

我找不到它(我认为它只是一个不错的、简单的 os.mount())。

当然,没有。 这个函数在 Windows 上会做什么?

请改用 shell 命令。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM