How can I mount and unmount Linux filesystems using 'ctypes', 'mount' and 'umount'
16:04 26 Jul 2017

I have a Python script (run as root) that needs to be able to mount and unmount the filesystem of a USB flash drive.

I’ve did some research, and I found the answer How do I mount a filesystem using Python? which uses ctypes. However, the answer only specifies how to mount, so I’ve tried to create a similar function to unmount the device. So all in all I have is this:

import os
import ctypes

def mount(source, target, fs, options=''):
    ret = ctypes.CDLL('libc.so.6', use_errno=True).mount(source, target, fs, 0, options)
    if ret < 0:
        errno = ctypes.get_errno()
        raise RuntimeError("Error mounting {} ({}) on {} with options '{}': {}".
                           format(source, fs, target, options, os.strerror(errno)))

def unmount(device, options=0):
    ret = ctypes.CDLL('libc.so.6', use_errno=True).umount2(device, options)
    if ret < 0:
        errno = ctypes.get_errno()
        raise RuntimeError("Error umounting {} with options '{}': {}".format(device, options, os.strerror(errno)))

However, trying the unmount command with option "0" or "1" like:

unmount('/dev/sdb', 0)

or

unmount('/dev/sdb', 1)

gives the following error:

Traceback (most recent call last):
  File "./BuildAndInstallXSystem.py", line 265, in 
    prepare_root_device()
  File "./BuildAndInstallXSystem.py", line 159, in prepare_root_device
    unmount('/dev/sdb', 0)
  File "./BuildAndInstallXSystem.py", line 137, in unmount
    raise RuntimeError("Error umounting {} with options '{}': {}".format(device, options, os.strerror(errno)))
RuntimeError: Error umounting /dev/sdb with options '0': Device or resource busy

while running it with 2 as the option:

unmount('/dev/sdb', 2)

unmounts all my filesystems, including '/', resulting in a system crash.

All of this still applies even if I replace the device number with the specific partition:

/dev/sdb -> /dev/sdb1

What am I doing wrong?

python linux ctypes mount umount