How can I run a python script at startup as root using Startup Applications?

There are two parts to this question: using Startup Applications to select what runs on session startup and how to avoid having to enter your password when running the script non-interactively.

For the first part, you need to create a new file with a .desktop extension in /home/zenzen/.config/autostart (change your username accordingly). For a simple script, the contents can look something like this:

[Desktop Entry]
Type=Application
Exec=/bin/bash -c "sudo /home/zenzen/autoclicker.py"
Terminal=true
Name=Autoclicker
Comment=A descriptive comment

This will make a new entry available when you launch the Startup Applications:

Obviously, adjust the Exec line to point to the right location as per your needs. Notice that in order to invoke sudo we need to pass in the command to bash, as it would normally be done directly on the terminal.

For the second part, create a new exception rule that will allow your user to run this specific command without entering your password. To do that, create a new file in /etc/sudoers.d. The name doesn't matter, and the contents should be a single line:

zenzen ALL=(ALL:ALL) NOPASSWD:/home/zenzen/autoclicker.py

Again, change the user and path to the script file with your own. You can logout from your account and log back in, and test if it's already working.

Note that there are other ways to do this but it all depends on your particular needs. I think this is a simple enough way to go about doing this.

6 Likes