如何使用Python挂载网络目录?

11 投票
4 回答
33939 浏览
提问于 2025-04-15 19:04

我需要在一台Linux机器上,用Python把一个叫“dir”的文件夹挂载到一台网络机器“data”上。

我知道可以通过命令行发送这个命令:

mkdir ~/mnt/data_dir
mount -t data:/dir/ ~/mnt/data_dir

但是我想知道怎么从Python脚本里发送这些命令呢?

4 个回答

7

我在一个没有挂载proc的chroot环境中试过这个。

/ # python
Python 2.7.1 (r271:86832, Feb 26 2011, 00:09:03) 
[GCC 4.4.5] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> from ctypes import *
>>> libc = cdll.LoadLibrary("libc.so.0")
>>> os.listdir("/proc")
[]
>>> libc.mount(None, "/proc", "proc", 0, None)
0
>>> os.listdir("/proc")
['vmnet', 'asound', 'sysrq-trigger', 'partitions', 'diskstats', 'crypto', 'key-users', 'version_signature', 'kpageflags', 'kpagecount', 'kmsg', 'kcore', 'softirqs', 'version', 'uptime', 'stat', 'meminfo', 'loadavg', 'interrupts', 'devices', 'cpuinfo', 'cmdline', 'locks', 'filesystems', 'slabinfo', 'swaps', 'vmallocinfo', 'zoneinfo', 'vmstat', 'pagetypeinfo', 'buddyinfo', 'latency_stats', 'kallsyms', 'modules', 'dma', 'timer_stats', 'timer_list', 'iomem', 'ioports', 'execdomains', 'schedstat', 'sched_debug', 'mdstat', 'scsi', 'misc', 'acpi', 'fb', 'mtrr', 'irq', 'cgroups', 'sys', 'bus', 'tty', 'driver', 'fs', 'sysvipc', 'net', 'mounts', 'self', '1', '2', '3', '4', '5', '6', '7', '8' ..........

你应该可以把设备文件从“无”改成mount()函数对网络共享所期待的格式。我记得这个格式和挂载命令“host:/path/to/dir”是一样的。

11

我建议你使用 subprocess.checkcall

from subprocess import *

#most simply
check_call( 'mkdir ~/mnt/data_dir', shell=True )
check_call( 'mount -t whatever data:/dir/ ~/mnt/data_dir', shell=True )


#more securely
from os.path import expanduser
check_call( [ 'mkdir', expanduser( '~/mnt/data_dir' ) ] )
check_call( [ 'mount', '-t', 'whatever', 'data:/dir/', expanduser( '~/mnt/data_dir' ) ] )
1

这里有一种方法:

import os

os.cmd ("mkdir ~/mnt/data_dir mount -t data:/dir/ /mnt/data_dir")

如果你想在你的脚本中读取命令的输出,也可以使用“popen”。

希望这对你有帮助。

...richie

撰写回答