How do I run a script on Unity login/logout?

I have two scripts - one to mount some folders over SSHFS - and one to unmount.

I would like to launch the mount script when my default Ubuntu desktop is launched (after I log in at the graphical console) - and the unmount script when I "Log Out..." from the cog-wheel at the top-right of the desktop.

Please can someone tell me how to achieve this? What are the most convenient/standard hooks to run commands on desktop launch / exit?


Solution 1:

Considering your requirement of running a job when you login to Unity and not for other logins, an Upstart session job seems perfect.

You may have noticed it: processes that you run after a GUI login are under a second init process. This init is a proper Upstart init, and you can start and stop session jobs based on events emitted by it. No root privileges needed at all. Better yet (or worse depending on the perspective), this is not yet completely supported for headless systems. An SSH login didn't start the user init from a quick test that I made just now.

To create a session job, make a new .conf file in ~/.config/upstart. That's the default primary directory for Upstart session jobs ($XDG_CONFIG_HOME/upstart), create it if doesn't exist. Here's an example job:

tee ~/.config/upstart/myjob.conf <<EOF
description "My job"
start on desktop-start
stop on desktop-end

script 
       firefox 'http://upstart.ubuntu.com/cookbook/#session-job'
end script
EOF

You can manually control it:

start myjob 
# or
initctl start myjob

The service command are used to control system jobs (those in /etc/init.d or /etc/init). For controlling session jobs, one needs to use the initctl command, which is used to interact with Upstart.

See man upstart-events for more events you can use.

Solution 2:

The solution was to use upstart tasks. I required two tasks - one fired when the desktop initializes for a user; the second when the users session expires. The following two scripts work for me under Ubuntu 14.04.

In ~/.config/upstart/desktopOpen.conf

description "Desktop Open Task"
start on desktop-start
task
script
# Commands to mount sshfs go here as shell-script.
end script

In ~/.config/upstart/desktopClose.conf

description "Desktop Close Task"
start on session-end
task
script
# Commands to unmount sshfs go here as shell-script.
end script

My fingers are crossed that these events will continue to meet requirements in future Ubuntu releases. I thought it worth posting my solution here - in case it is of use to others.