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"
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).
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
精彩评论