如何从命令行自动挂载?


25

如何从命令行触发自动挂载?“自动挂载”并不是指全自动挂载,而是获得可用设备的列表,然后选择一个并最终显示为/media/{user}/{diskid}。例如,该功能由Nautilus或Thunar提供,但是我似乎找不到找到触发这种半自动安装的命令行工具。

pmount是我发现的最接近的,但似乎是由下面完全不同的机制工作的,并使设备显示为/media/sdf直线。

Answers:


29

您可以使用:

udisksctl挂载-b device_name

device_name存储设备的名称在哪里,应类似于/dev/sdb1

使用lsblksudo fdisk -l命令,您可以找到连接到系统的所有存储设备。


2
尝试过,但是导致的结果与/media/{disk}Thunar或Nautilus给出的结果不同。但是,udisksctl提供的命令udisks2似乎可以满足我的要求。
Grumbel 2013年

1
udisksctl status将给出正确的设备列表并以用户身份工作。fdisk -l不仅需要root用户,而且GPT驱动器也会失败。cat /proc/partitions这将是一种更好的了解可用分区的底层方法。
Grumbel 2013年

udiskctl对于在没有root用户特权的情况下将映像磁盘文件装入循环设备也非常有用!

似乎udisk可以使用到14.04。
Pablo A

13

gio mount

现在已将gvfs列为已弃用(2018),建议您使用Giome In Out和Glib的一部分``gio''。参见维基百科

例如,自动挂载第二个驱动器分区;使用以下命令创建具有可执行权限的bash脚本以在启动时运行:

gio mount -d /dev/sda2

如果您是该分区的所有者(请参阅chown参考资料),则不需要sudo。

要挂载一个ISO文件,例如~/ISOs

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

你可以URL编码与Python 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在mount命令中使用输出,因为--list不会显示块设备名称,而尝试使用它在安装中打印的设备名称将导致:

Error mounting location: volume doesn't implement mount

结论

虽然两者gvfs-mountudisksctl会为执行这些任务,它们的接口是不切实际的,因为他们不提供磁盘的人类可读的状态可用,只是一个过于冗长的信息转储。


1
您能否扩展您的答案,包括如何使用iso进行安装gio mount?在18.04上gio mount -l返回了Archive Mounter,Type: GDaemonMount但我无法通过CLI挂载它(可能是问题?)。
Pablo A

6

一个简单的解决方案,可以根据需要工作(挂载到/ media / {user} / {diskid}),除了它不能列出设备,但需要为其指定确切的,区分大小写的卷标签作为参数$ 1。

安装

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注意不要将放在/前面home。如果您使用cd /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
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.