0

How can I create(and remove if unplugged) a symlink to the mount-point of a newly plugged-in USB-device on the desktop or in the $HOME of the systems guest-account?

4
  • Is that USB-device always the same one ? Is it a usb memory stick or a HDD/SDD ? Assuming you use Unity, would a relevant icon with mounted volume name appearing in the launch bar serve yr purpose, instead of having an (s-link) icon pop-up on the desktop ?
    – Cbhihe
    Feb 20, 2016 at 9:08
  • Cbhihe - the usb device is always some kind of storage device(mostly usb-memory stick), but not always the same and a launcher icon doesn't help it needs to be a symlink in the homedirectory of the currently logged in user(guest-account most of the time)
    – Florian L.
    Feb 21, 2016 at 16:33
  • An USB device, inserted when in a guest session, will normally be mounted in /media/guest-XXXXXX. Since the username is unique for each session, creating a symlink would be a little tricky. Can you elaborate on why you would need such a symlink? Feb 21, 2016 at 17:24
  • To answer Jacobs question, it's wouldn't be a problem if it would also run for other accounts. The problem that our users have, is that we use some java-tools that do not use the gnome-file-dialog but instead use the rather minimal jfiledialog. That does not have a devices list on the left hand side, and only presents the users with a list of "/", /home" etc. Since our users can be pretty linux iliterate they are dependend on the gui to provide them a visible link to their usb-drives, so the workaround-idea is to create a link to the usb-drives there.
    – Florian L.
    Feb 28, 2016 at 15:20

1 Answer 1

1

Your question turns out to exist of two separate questions:

  1. How to automatically create (and remove) a link on the desktop to mounted usb drives
  2. How to run it on guest account

These questions are answered in [1.] and [2.] below.

1. Automatically create a desktop link to mounted usb drives (in general)

With a small background script, you can automatically have a link created on your desktop to the mounted usb drive(s), and automatically have it removed if the drive is removed.

enter image description hereenter image description here

The procedure; how it works

The script below is an edited version of this one. This version:

  • keeps an eye on newly mounted devices (using the command lsblk)
  • if a new item shows up, it checks if the newly mounted device is a usb device by the command: find /dev/disk -ls | grep <disk>. If usb in the output, the new mount is valid.
  • if the mount is valid, a link is created on the user's desktop, with the command: ln -s <new_mount> <target>.
    The targeted link is named: [USB] <devicename>.

At the same time

  • The new mount is added to a list. periodically (once per four seconds), the list is checked. If the mount no longer exists, its corresponding link is removed from your desktop.

How to set up

  1. Copy the script below into an empty file, save it as show_usb.py
  2. create the directory /opt/show_usb (since we want to run it for a guest account):

    sudo mkdir /opt/show_usb
    
  3. Copy the script into /opt/show_usb:

    sudo cp /path/to/show_usb.py /opt/show_usb
    
  4. Test-run the script from a terminal by the command:

    python3 /opt/show_usb/show_usb.py
    
  5. If all works fine, add it to Startup Applications: Dash > Startup Applications > Add. Add the command:

    python3 /opt/show_usb/show_usb.py
    

The script

#!/usr/bin/env python3
import os
import subprocess
import time

def find_dtop():
    # get the localized path to the Desktop folder
    home = os.environ["HOME"]; dr_file = home+"/.config/user-dirs.dirs"
    return [home+"/"+ l.split("/")[-1].strip() \
            for l in open(dr_file).readlines() \
            if l.startswith("XDG_DESKTOP_DIR=")][0].replace('"', "")

def get_mountedlist():
    return [(item.split()[0].replace("├─", "").replace("└─", ""),
             item[item.find("/"):]) for item in subprocess.check_output(
            ["lsblk"]).decode("utf-8").split("\n") if "/" in item]

def identify(disk):
    cmd = "find /dev/disk -ls | grep /"+disk
    output = subprocess.check_output(["/bin/bash", "-c", cmd]).decode("utf-8")
    return True if "usb" in output else False

done = []; check = []
dt = find_dtop()
while True:
    mnt = get_mountedlist(); mount_check = [item[1] for item in mnt]
    for item in check:
        if not item in mount_check:
            try:
                os.remove(dt+"/[USB] "+item.split("/")[-1]); check.remove(item)
            except FileNotFoundError:
                pass
    new_paths = [dev for dev in mnt if not dev in done and not dev[1] == "/"]
    valid = [dev for dev in new_paths if identify(dev[0]) == True]
    for item in valid:
        new = item[1]
        subprocess.Popen(["ln", "-s", new, dt+"/[USB] "+new.split("/")[-1] ])
        check.append(new)
    time.sleep(4)
    done = mnt




2. How to automatically run the script, specifically in guest account

To make the script autostart in a guest session:

  1. Look if the directory /etc/guest-session/skel/.config/autostart exists. If not, create it:

    sudo mkdir -p /etc/guest-session/skel/.config/autostart
    
  2. Now create a startup launcher for the guest account:

    sudo -i gedit /etc/guest-session/skel/.config/autostart/desktop_usb.desktop
    

    In the file that opens, paste the code below:

    [Desktop Entry]
    Name=USB_desktop
    Exec=python3 /opt/show_usb/show_usb.py
    Type=Application
    

    Save and close the file. Now when you log in on guest account, the script will run.

That's it

Notes

  • More on how to edit the guest account to be found here.
  • The script only acts if a new drive is mounted and adds no noticeable load to the processor whatsoever.
5
  • 1
    /etc/skel is used for new regular accounts, so you should not mess with it only to affect guest sessions. If /etc/guest-session/skel does not exist, just create it! Feb 22, 2016 at 13:15
  • 1
    @GunnarHjalmarsson Thanks for the hint! That will simplify the last section. Will edit... Feb 22, 2016 at 13:27
  • thanks for the answer and sorry for the late response, work had me pretty occupied the last week, I'll try it as soon as possible.
    – Florian L.
    Feb 28, 2016 at 15:27
  • Hey Jacob, sorry it tried the answer a few weeks ago but forgot to check it here, it works perfectly for what were trying to do.. Thank you very much.
    – Florian L.
    Mar 11, 2016 at 13:06
  • @FlorianL. you're welcome :) Mar 11, 2016 at 13:50

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .