명령 줄에서 자동 마운트하는 방법?


25

명령 줄에서 자동 마운트를 어떻게 트리거 할 수 있습니까? "자동 마운트"란 완전 자동 마운팅을 의미하는 것이 아니라 사용 가능한 장치 목록을 가져 와서 하나를 선택하여로 끝 /media/{user}/{diskid}냅니다. 이 기능은 예를 들어 노틸러스 또는 Thunar에서 제공하지만 이러한 종류의 반자동 마운트를 트리거하는 명령 줄 도구를 찾지 못하는 것 같습니다.

pmount내가 찾은 가장 근접하지만 아래 완전히 다른 역학에 의해 작동하는 것으로 보이며 장치 /media/sdf가 선을 ​​따라 표시 되거나 무언가를 표시합니다 .

답변:


29

당신이 사용할 수있는:

udisksctl 마운트 -b device_name

어디에device_name 저장 장치의 이름이며 다음과 같아야 /dev/sdb1합니다.

lsblk또는 sudo fdisk -lcommand를 사용하면 시스템에 연결된 모든 저장 장치를 찾을 수 있습니다.


2
그러나 /media/{disk}Thunar 또는 Nautilus가 제공하는 것과는 다른 결과로 이어졌습니다 . udisksctl에서 제공하는 명령 udisks2하지만 내가 원하는 것을 할 것 같다.
Grumbel

1
udisksctl status적절한 장치 목록을 제공하고 사용자로 작업합니다. fdisk -l루트가 필요할뿐만 아니라 GPT 드라이브에서도 실패합니다. cat /proc/partitions사용 가능한 파티션에 대한 아이디어를 얻는 더 나은 저수준 방법입니다.
Grumbel

udiskctl루트 권한없이 이미지 디스크 파일을 루프 장치에 마운트하는 데 매우 유용합니다!

udisk14.04까지 사용할 수있는 것 같습니다 .
파블로 A

13

gio mount

gvfs 는 이제 더 이상 사용되지 않는 것으로 표시되며 (2018) Gnome In Out 및 Glib의 일부인 'gio'를 사용하는 것이 좋습니다. Wikipedia를 참조하십시오 .

예를 들어, 두 번째 드라이브 파티션을 자동 마운트합니다. 다음 명령으로 시작시 실행할 실행 권한이있는 bash 스크립트를 작성하십시오.

gio mount -d /dev/sda2

파티션 소유자 인 경우 (참조 chown) sudo가 필요하지 않습니다.

예를 들어 ~/ISOs다음 위치에있는 ISO 파일을 마운트하려면

gio mount "archive://file%3A%2F%2F%2Fhome%2Fpablo%2FISOs%2Fubuntu-18.04-desktop-amd64.iso"

당신은 수있는 URL 인코딩 파이썬 3 경로 realpath(에 연결하는을 archive://:

python -c "import urllib.parse, sys; print(urllib.parse.quote(sys.argv[1] if len(sys.argv) > 1 else sys.stdin.read()[0:-1], \"\"))" "file://$(realpath ubuntu-18.04-desktop-amd64.iso)"

에 탑재됩니다 /run/user/$(id -u)/gvfs/.

대안으로 gnome-disk-image-mounter계속됩니다 /media/$USER/.

마운트를 해제하려면 gio mount -u /run/user/$(id -u)/gvfs/archive*(또는 마운트 /media/$USER/한 방식에 따라).

udisksctl

사용 가능한 장치 나열 :

udisksctl status

장착은 다음을 통해 수행됩니다.

udisksctl mount -b /dev/sdf

또는

udisksctl mount -p block_devices/sdf

마운트 해제는 다음을 통해 수행됩니다.

udisksctl unmount -b /dev/sdf

또는

udisksctl unmount -p block_devices/sdf

다음 object-path을 수행하여 찾을 수 있습니다.

udisksctl dump

유형의 객체는 org.freedesktop.UDisks2.Block로 유효한 것으로 보입니다 object-patch. /org/freedesktop/UDisks2/접두사는 udisksctl의 경로에서 잘라 내야합니다.

gvfs-mount

사용 가능한 장치 나열은 다음을 통해 수행 할 수 있습니다.

gvfs-mount --list

다음과 같이 마운트 할 수 있습니다.

gvfs-mount -d /dev/sdf

마운트 해제는 다음을 통해 가능합니다.

gvfs-mount --unmount /media/user/01234567890

남아있는 문제 중 하나 는 블록 장치 이름을 표시하지 않고 마운트에서 인쇄하는 장치 이름을 사용하려고 gvfs-mount --list하면 마운트 명령에서 출력 을 사용하는 방법을 모른다 --list는 것입니다.

Error mounting location: volume doesn't implement mount

결론

이 두 가지 방법 모두 gvfs-mountudisksctl작업을 위해 작동 할 그들이 정보를 덤프 자세한 그냥 지나치게 사용 가능한 디스크의 사람이 읽을 수있는 상태를 제공하지 않는 한, 자신의 인터페이스는 비현실적이다.


1
iso를 마운트하는 방법을 포함하여 답변을 확장 할 수 gio mount있습니까? 18.04에서 Archive Mounter가 gio mount -l반환 Type: GDaemonMount되었지만 CLI를 통해 마운트 할 수 없었습니다 ( 문제 일 수 있습니까?).
파블로 A

6

장치를 나열 할 수 없지만 대소 문자를 구분하는 정확한 볼륨 레이블을 인수 $ 1로 제공해야한다는 점을 제외하고는 필요에 따라 작동하는 간단한 솔루션 (/ media / {user} / {diskid}에 마운트)

마운트하려면 :

DEVICE=$(findfs LABEL=$1) && udisksctl mount -b $DEVICE

마운트 해제 :

DEVICE=$(findfs LABEL=$1) && udisksctl unmount -b $DEVICE

좋은. udisksctl mount -b $(findfs LABEL=<label>)
브렌트 파우스트

1

문제가 발생하여 다음 해결책을 찾았습니다.

udisksctl mount -b /dev/disk/by-labels/$LABEL

사용자 비밀번호이고 이미 로그인 한 경우에도 사용자 비밀번호를 묻습니다.


0

이 문제를 해결하기 위해이 Bash 스크립트를 작성했지만 스크립트 초보자입니다. 모든 제안을 환영합니다! 스크립트 아래에 사용법과 설명이 나와 있습니다.

#!/bin/bash
# umanage.sh
# 2014-05-05

BASEPATH="/media/$(whoami)/"
RESULTS=$(udisksctl dump | grep IdLabel | grep -c -i "$1")

case "$RESULTS" in

0 )     echo "Nothing found."
        ;;

1 )     DEVICELABEL=$(udisksctl dump | grep IdLabel | grep -i "$1" | cut -d ":" -f 2 | sed 's/^[ \t]*//')
        DEVICE=$(udisksctl dump | grep -i "IdLabel: \+$DEVICELABEL" -B 12 | grep " Device:" | cut -d ":" -f 2 | sed 's/^[ \t]*//')
        DEVICEPATH="$BASEPATH""$DEVICELABEL"

        if [[ -z $(mount | grep "$DEVICE") ]]
        then
                echo "Found unmounted $DEVICE partition."
                echo "Do you want to mount it in $DEVICEPATH?"
                select yn in "Mount" "Ignore"
                do
                        case $yn in
                        Mount )         udisksctl mount -b "$DEVICE"
                                        break
                                        ;;
                        Ignore )        exit
                                        ;;
                        esac
                done
        else
                echo "Found $DEVICE partition, currently mounted in $DEVICEPATH."
                echo "Do you want to unmount it?"
                select yn in "Unmount" "Ignore"
                do
                        case $yn in
                        Unmount )       udisksctl unmount -b "$DEVICE"
                                        break
                                        ;;
                        Ignore )        exit
                                        ;;
                        esac
                done
        fi
        ;;

* )     if [ $# -eq 0 ]
        then
                echo "No argument supplied"
        else
                echo "$RESULTS possible results. You may be looking for:"
                echo
                udisksctl dump | grep IdLabel | grep -i "$1" | cut -d ":" -f 2 | sed 's/^[ \t]*//' | sed '/^$/d'
                echo
                echo "Please refine your search."
        fi
        ;;

esac

용법:

  • 스크립트를 umanage.sh로 저장하십시오.
  • 실행 가능하게 만드십시오 : chmod + x umanage.sh
  • 그것을 실행하십시오 : ./umanage.sh YourDeviceLabel

스크립트는 마운트하려는 파티션의 레이블을 인수로 승인하고 udisksctl 덤프에서 해당 항목을 찾습니다.

파티션이 있고 마운트되지 않은 경우 장치 이름과 경로가 표시되고 파티션을 마운트하라는 메시지가 표시됩니다. 스크립트는 부분 레이블도 검색하며 대문자 나 소문자를 신경 쓰지 않습니다 (정확한 레이블을 기억하지 못하는 경우에 유용합니다).

./umanage.sh PASSPORT
Found unmounted /dev/sdf1 partition.
Do you want to mount it in /media/pixel/My Passport?
1) Mount
2) Ignore
#? 

파티션이 있고 이미 마운트 된 경우 마운트를 해제하라는 메시지가 나타납니다.

./umanage.sh passp
Found /dev/sdf1 partition, currently mounted in /media/open/My Passport.
Do you want to unmount it?
1) Unmount
2) Ignore
#?

인수가 결과 이상인 경우 스크립트는 일치하는 파티션 레이블을 표시하고 검색을 세분화하도록 요청합니다.

./umanage.sh SS
2 possible results. You may be looking for:

SSD-9GB
My Passport

Please refine your search.

0

드라이브를 마운트하는 스크립트- mount-menu.sh

mount-menu.sh스크립트를 사용하면 마운트 해제 할 드라이브 / 파티션을 선택할 수 있습니다. 스크립트를 호출하려면 다음을 사용하십시오 sudo mount-menu.sh.. 이 화면은 고유 한 머신 환경에 맞게 나타납니다.

마운트 메뉴 1.png

  • 화살표 키를 사용하여 파티션을 선택하고 Enter

메뉴는이 정보를 지우고 터미널에 둡니다.

=====================================================================
Mount Device:  /dev/nvme0n1p10
Mount Name:    /mnt/mount-menu.FPRAW
File System:   ext4
ID:            Ubuntu
RELEASE:       18.04
CODENAME:      bionic
DESCRIPTION:   Ubuntu 18.04.1 LTS
 Size  Used Avail Use%
  27G  7.9G   18G  32%

이제 다음을 사용 cd /mnt/mount-menu.FPRAW하여 외부 드라이브의 파티션에 액세스 할 수 있습니다 .

그런 다음 앞에 표시 cd home/YOUR_NAME하지 않도록주의하면서 사용할 수 있습니다 . 사용 하면 부트 드라이브로 이동하여 외부 드라이브에서 벗어날 수 있습니다./homecd /home

mount-menu.sh 스크립트 내용

스크립트를 작성하려면 터미널을 열고 다음을 입력하십시오.

sudo -H gedit /usr/local/bin/mount-menu.sh

그런 다음 아래 코드를 복사하여에 붙여 넣으십시오 gedit. 파일을 저장하고 종료하십시오 gedit.

이제 다음을 사용하여 파일을 실행 파일로 표시하십시오.

sudo chmod a+x /usr/local/bin/mount-menu.sh

복사 할 스크립트는 다음과 같습니다.

#!/bin/bash

# NAME: mount-menu.sh
# PATH: /usr/local/bin
# DESC: Select unmounted partition for mounting
# DATE: May 9, 2018. Modified May 11, 2018.

# $TERM variable may be missing when called via desktop shortcut
CurrentTERM=$(env | grep TERM)
if [[ $CurrentTERM == "" ]] ; then
    notify-send --urgency=critical \ 
                "$0 cannot be run from GUI without TERM environment variable."
    exit 1
fi

# Must run as root
if [[ $(id -u) -ne 0 ]] ; then echo "Usage: sudo $0" ; exit 1 ; fi

#
# Create unqique temporary file names
#

tmpMenu=$(mktemp /tmp/mount-menu.XXXXX)     # Menu list
tmpInfo=$(mktemp /tmp/mount-menu.XXXXX)     # Mount Parition Info
tmpWork=$(mktemp /tmp/mount-menu.XXXXX)     # Work file
MountName=$(mktemp -d /mnt/mount-menu.XXXXX)  # Mount directory name

#
# Function Cleanup () Removes temporary files
#

CleanUp () {
    [[ -f $tmpMenu ]] && rm -f $tmpMenu     # If temporary files created
    [[ -f $tmpInfo ]] && rm -f $tmpInfo     #  at various program stages
    [[ -f $tmpWork ]] && rm -f $tmpWork     #  remove them before exiting.
}


#
# Mainline
#

lsblk -o NAME,FSTYPE,LABEL,SIZE,MOUNTPOINT > $tmpMenu

i=0
SPACES='                                                                     '
DoHeading=true
AllPartsArr=()      # All partitions.

# Build whiptail menu tags ($i) and text ($Line) into array

while read -r Line; do
    if [[ $DoHeading == true ]] ; then
        DoHeading=false                     # First line is the heading.
        MenuText="$Line"                    # Heading for whiptail.
        FSTYPE_col="${Line%%FSTYPE*}"           
        FSTYPE_col="${#FSTYPE_col}"         # FS Type, ie `ext4`, `ntfs`, etc.
        MOUNTPOINT_col="${Line%%MOUNTPOINT*}"
        MOUNTPOINT_col="${#MOUNTPOINT_col}" # Required to ensure not mounted.
        continue
    fi

    Line="$Line$SPACES"                     # Pad extra white space.
    Line=${Line:0:74}                       # Truncate to 74 chars for menu.

    AllPartsArr+=($i "$Line")               # Menu array entry = Tag# + Text.
    (( i++ ))

done < $tmpMenu                             # Read next "lsblk" line.

#
# Display whiptail menu in while loop until no errors, or escape,
# or valid partion selection .
#

DefaultItem=0

while true ; do

    # Call whiptail in loop to paint menu and get user selection
    Choice=$(whiptail \
        --title "Use arrow, page, home & end keys. Tab toggle option" \
        --backtitle "Mount Partition" \
        --ok-button "Select unmounted partition" \
        --cancel-button "Exit" \
        --notags \
        --default-item "$DefaultItem" \
        --menu "$MenuText" 24 80 16 \
        "${AllPartsArr[@]}" \
        2>&1 >/dev/tty)

    clear                                   # Clear screen.
    if [[ $Choice == "" ]]; then            # Escape or dialog "Exit".
        CleanUp
        exit 1;
     fi

    DefaultItem=$Choice                     # whiptail start option.
    ArrNdx=$(( $Choice * 2 + 1))            # Calculate array offset.
    Line="${AllPartsArr[$ArrNdx]}"          # Array entry into $Line.

    # Validation - Don't wipe out Windows or Ubuntu 16.04:
    # - Partition must be ext4 and cannot be mounted.

    if [[ "${Line:MOUNTPOINT_col:4}" != "    " ]] ; then
        echo "Partition is already mounted."
        read -p "Press <Enter> to continue"
        continue
    fi

    # Build "/dev/Xxxxx" FS name from "├─Xxxxx" menu line
    MountDev="${Line%% *}"
    MountDev=/dev/"${MountDev:2:999}"

    # Build File System Type
    MountType="${Line:FSTYPE_col:999}"
    MountType="${MountType%% *}"

    break                                   # Validated: Break menu loop.

done                                        # Loop while errors.

#
# Mount partition
#

echo ""
echo "====================================================================="
mount -t auto $MountDev $MountName


# Display partition information.
echo "Mount Device=$MountDev" > $tmpInfo
echo "Mount Name=$MountName" >> $tmpInfo
echo "File System=$MountType" >> $tmpInfo

# Build Mount information (the partition selected for cloning to)
LineCnt=$(ls $MountName | wc -l)
if (( LineCnt > 2 )) ; then 
    # More than /Lost+Found exist so it's not an empty partition.
    if [[ -f $MountName/etc/lsb-release ]] ; then
        cat $MountName/etc/lsb-release >> $tmpInfo
    else
        echo "No LSB-Release file on Partition." >> $tmpInfo
    fi
else
    echo "Partition appears empty" >> $tmpInfo
    echo "/Lost+Found normal in empty partition" >> $tmpInfo
    echo "First two files/directories below:" >> $tmpInfo
    ls $MountName | head -n2 >> $tmpInfo
fi

sed -i 's/DISTRIB_//g' $tmpInfo      # Remove DISTRIB_ prefix.
sed -i 's/=/:=/g' $tmpInfo           # Change "=" to ":="
sed -i 's/"//g' $tmpInfo             # Remove " around "Ubuntu 16.04...".

# Align columns from "Xxxx:=Yyyy" to "Xxxx:      Yyyy"
cat $tmpInfo | column -t -s '=' > $tmpWork
cat $tmpWork > $tmpInfo

# Mount device free bytes
df -h --output=size,used,avail,pcent "$MountDev" >> $tmpInfo

# Display partition information.
cat $tmpInfo

CleanUp                             # Remove temporary files

exit 0

umount-menu.sh 드라이브 / 파티션 마운트 해제

스크립트에 대해 파일 작성 / 실행 비트 표시 프로세스를 반복하십시오 umount-menu.sh. 이 스크립트는에 의해 마운트 된 드라이브 / 파티션 만 마운트 해제합니다 mount-menu.sh. 동일한 선택 메뉴가 있으며 메시지와 함께 완료됩니다.

=====================================================================

/dev/nvme0n1p10 mounted on /mnt/mount-menu.FPRAW unmounted.

스크립트를 호출하려면 다음을 사용하십시오. sudo umount-menu.sh

umount-menu.sh bash 스크립트 :

!/bin/bash

# NAME: umount-menu.sh
# PATH: /usr/local/bin
# DESC: Select mounted partition for unmounting
# DATE: May 10, 2018. Modified May 11, 2018.

# $TERM variable may be missing when called via desktop shortcut
CurrentTERM=$(env | grep TERM)
if [[ $CurrentTERM == "" ]] ; then
    notify-send --urgency=critical \ 
                "$0 cannot be run from GUI without TERM environment variable."
    exit 1
fi

# Must run as root
if [[ $(id -u) -ne 0 ]] ; then echo "Usage: sudo $0" ; exit 1 ; fi

#
# Create unqique temporary file names
#

tmpMenu=$(mktemp /mnt/mount-menu.XXXXX)   # Menu list

#
# Function Cleanup () Removes temporary files
#

CleanUp () {
    [[ -f "$tmpMenu" ]] && rm -f "$tmpMenu" #  at various program stages
}


#
# Mainline
#

lsblk -o NAME,FSTYPE,LABEL,SIZE,MOUNTPOINT > "$tmpMenu"

i=0
SPACES='                                                                     '
DoHeading=true
AllPartsArr=()      # All partitions.

# Build whiptail menu tags ($i) and text ($Line) into array

while read -r Line; do
    if [[ $DoHeading == true ]] ; then
        DoHeading=false                     # First line is the heading.
        MenuText="$Line"                    # Heading for whiptail.
        MOUNTPOINT_col="${Line%%MOUNTPOINT*}"
        MOUNTPOINT_col="${#MOUNTPOINT_col}" # Required to ensure mounted.
        continue
    fi

    Line="$Line$SPACES"                     # Pad extra white space.
    Line=${Line:0:74}                       # Truncate to 74 chars for menu.

    AllPartsArr+=($i "$Line")               # Menu array entry = Tag# + Text.
    (( i++ ))

done < "$tmpMenu"                           # Read next "lsblk" line.

#
# Display whiptail menu in while loop until no errors, or escape,
# or valid partion selection .
#

DefaultItem=0

while true ; do

    # Call whiptail in loop to paint menu and get user selection
    Choice=$(whiptail \
        --title "Use arrow, page, home & end keys. Tab toggle option" \
        --backtitle "Mount Partition" \
        --ok-button "Select unmounted partition" \
        --cancel-button "Exit" \
        --notags \
        --default-item "$DefaultItem" \
        --menu "$MenuText" 24 80 16 \
        "${AllPartsArr[@]}" \
        2>&1 >/dev/tty)

    clear                                   # Clear screen.

    if [[ $Choice == "" ]]; then            # Escape or dialog "Exit".
        CleanUp
        exit 1;
     fi

    DefaultItem=$Choice                     # whiptail start option.
    ArrNdx=$(( $Choice * 2 + 1))            # Calculate array offset.
    Line="${AllPartsArr[$ArrNdx]}"          # Array entry into $Line.

    if [[ "${Line:MOUNTPOINT_col:15}" != "/mnt/mount-menu" ]] ; then
        echo "Only Partitions mounted by mount-menu.sh can be unounted."
        read -p "Press <Enter> to continue"
        continue
    fi

    # Build "/dev/Xxxxx" FS name from "├─Xxxxx" menu line
    MountDev="${Line%% *}"
    MountDev=/dev/"${MountDev:2:999}"

    # Build Mount Name
    MountName="${Line:MOUNTPOINT_col:999}"
    MountName="${MountName%% *}"

    break                                   # Validated: Break menu loop.

done                                        # Loop while errors.

#
# Unmount partition
#

echo ""
echo "====================================================================="
umount "$MountName" -l                      # Unmount the clone
rm  -d "$MountName"                         # Remove clone directory

echo $(tput bold)                           # Set to bold text
echo $MountDev mounted on $MountName unmounted.
echo $(tput sgr0)                           # Reset to normal text

CleanUp                                     # Remove temporary files

exit 0
당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.