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

时间:2010-02-09 20:47:49

标签: python linux scripting mount

我需要在linux机器上使用python在网络机器“data”上挂载目录“dir”

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

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

但我如何从python脚本发送这些命令?

4 个答案:

答案 0 :(得分:9)

我建议您使用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 :(得分: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()函数对网络共享所期望的格式。我相信它与mount命令“host:/ path / to / dir”

相同

答案 2 :(得分:2)

这是一种方式:

import os

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

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

HIH

...里奇

答案 3 :(得分:2)

使用subprocess模块的示例:

import subprocess

subprocess.Popen(["mkdir", "~/mnt/data_dir", "mount", "-t", "data:/dir/", "/mnt/data_dir"])

OR

import subprocess

subprocess.Popen("mkdir ~/mnt/data_dir mount -t data:/dir/ /mnt/data_dir", shell=True)

第二个版本使用shell来执行命令。虽然在大多数情况下更易读,更易于使用,但在传递用户提交的参数时应该避免这种情况,因为这些参数可能导致shell注入(即在这种情况下执行除mkdir之外的其他命令)。