簡體   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