简体   繁体   中英

How to mount a network directory using python?

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?

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' ) ] )

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"

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

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 (ie execution of other commands than mkdir in this case).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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