How to mount a network directory using python?

懵懂的女人 提交于 2019-12-03 17:47:31

问题


I need to mount a directory "dir" on a network machine "data" using python on a linux machine

I know that I can send the command via command line:

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

but how would I send those commands from a python script?


回答1:


Here is one way:

import os

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

You can also use "popen" if you want to read the output of the command in your script.

HIH

...richie




回答2:


I'd recommend you use 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' ) ] )



回答3:


I tried this in a chroot without proc mounted

/ # 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' ..........

You should be able to change the device file from "None" to the format the mount() function expects for network shares. I believe it is the same as the mount command "host:/path/to/dir"




回答4:


Example using the subprocess module:

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)

The second version uses the shell to execute the command. While more readable and easier to use in most situations, it should be avoided when passing user submitted arguments as those might lead to shell injection (i.e. execution of other commands than mkdir in this case).



来源:https://stackoverflow.com/questions/2232420/how-to-mount-a-network-directory-using-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!