2

I want to execute a script much like the "Startup Applications", as documented officially, and explained in this great answer and asked about again in this question.

However, I have additional, very specific requirements

  • Restricted users should not be allowed to change the call to the script
  • The script should run AFTER session login (in the context of that user at best) and the just logged in username must be available to the script
  • The script should also run, if the user changes (Ubuntu allows the change of The user without logging out of the first one)

This renders out upstart (which runs at system startup AFAIK) and the standard Startup Application, because these are manageable even by restricted users.

Marcel
  • 255

1 Answers1

0

I think that what you are looking for is the systemd for user.

You can add a .service file inside a user directory:

~ve/.config/systemd/user/default.target.wants/

Call the file <something>.service.

# Documentation available at:
# https://www.freedesktop.org/software/systemd/man/systemd.service.html

[Unit] Description=This User Service After=foo.service

[Service] Type=simple WorkingDirectory=~ Environment="DISPLAY=:0" ExecStart=/usr/bin/script ExecStop=/bin/kill "$MAINPID" Restart=on-failure RestartSec=5

[Install] WantedBy=default.target

Obviously you want to tweak the parameters to fit your needs. This starts the process defined in ExecStart=... with whatever script or binary you need. The process starts when the user logs in. X11 will be running. The GDM may not be 100% started. However, you can start opening windows and it works as expected.

The process will keep running if you just switch between users. It will be stopped with the ExecStop=... when the user logs out.

If you want to run the script once, you want to change the type with Type=once and remove the Restart=... variables.

If you are creating a Debian package, you actually want to install that <something>.service file under:

/usr/lib/systemd/user/...

Then you need to enable the service for that user.

The clean way is to setup the daemon using the systemctl tool like so:

systemctl --user deamon-reload
systemctl --user unmask '<something>.service'
systemctl --user enable '<something>.service'

However, this is only if the user themself can run said commands.

Your package would have to install it manually otherwise. The following works when running as root:

mkdir -p /home/${USER}/.config/systemd/user/default.target.wants
chown -R ${USER}:${USER} /home/${USER}/.config/systemd
rm -f /home/${USER}/.config/systemd/user/default.target.wants/<something>.service
sudo -H -u ${USER} sh -c "ln -s /usr/lib/systemd/user/<something>.service /home/${USER}/.config/systemd/user/default.target.wants/<something>.service"

The sudo on the last line is to create the softlink as user ${USER}.

Alexis Wilke
  • 2,707