How to umount a usb drive from my app running in a docker container

You’re absolutely right - the permission issue persists on the host side. Here are several approaches to overcome this:

Option 1: Configure Sudoers for Passwordless Unmount

Add the torizon user to sudoers with specific permissions for unmount operations:

# Add to /etc/sudoers.d/usb-unmount
torizon ALL=(ALL) NOPASSWD: /bin/umount

Then modify your script to use:

sudo umount "$DEVICE" 2>/dev/null

Option 2: Use UDisks2 for User-Space Unmounting

UDisks2 allows non-root users to unmount removable devices. Install and use it:

# Install udisks2 if not present
sudo apt update && sudo apt install udisks2

# In your monitoring script, replace sudo umount with:
udisksctl unmount -b "$DEVICE" 2>/dev/null

Option 3: Leverage udev Rules for Automatic Management

Based on community experience with USB automounting (1), you can create custom udev rules that handle both mounting and unmounting. Create a udev rule that triggers scripts with appropriate permissions:

# /etc/udev/rules.d/99-usb-mount.rules
ACTION=="remove", SUBSYSTEM=="block", KERNEL=="sd[a-z][0-9]", RUN+="/usr/local/bin/usb-unmount.sh %k"

Option 4: Use systemd-mount for User Operations

Systemd provides user-space mounting capabilities:

# Instead of umount, use:
systemctl --user stop media-usb\\x2ddrive.mount 2>/dev/null

Option 5: Modify Script to Use User Groups

Ensure the torizon user is in appropriate groups for device access (2). The torizon user should already be mapped to several groups including those needed for hardware device access (2).

Recommended Approach: UDisks2

For your use case, I recommend Option 2 (UDisks2) as it’s designed specifically for user-space device management and doesn’t require modifying system security policies.

Modified monitoring script:

#!/bin/bash
# /home/torizon/usb-manager/monitor-unmount.sh

WATCH_DIR="/home/torizon/usb-manager"
REQUEST_FILE="$WATCH_DIR/unmount-request"
RESPONSE_FILE="$WATCH_DIR/unmount-response"

while true; do
    if [ -f "$REQUEST_FILE" ]; then
        DEVICE=$(cat "$REQUEST_FILE")
        
        # Use udisksctl instead of sudo umount
        if udisksctl unmount -b "$DEVICE" 2>/dev/null; then
            echo "SUCCESS: $DEVICE unmounted" > "$RESPONSE_FILE"
        else
            echo "ERROR: Failed to unmount $DEVICE" > "$RESPONSE_FILE"
        fi
        
        rm "$REQUEST_FILE"
    fi
    sleep 1
done

This approach maintains security while providing the functionality you need without requiring sudo privileges.

Best regards, Toradex AI Assistant.


Did you like my answer? :+1: :-1:

If I answered your question, please tick the “Solution” checkbox.

For follow-up questions to me, please use @ToradexAI in your post.