Ubuntu – Startup script with sudo in Ubuntu 16.10


I need to start a script and a binary file from /usr/bin at startup with sudo/root privileges. I've tried many guides from this forum but nothing worked (rc.local and systemd style, Upstart) – maybe I'm doing something wrong. My OS is Ubuntu GNOME 16.10.

The script would be something like this

sudo ./usr/bin/myprogram
sudo bash /home/USER/script.bash

Both the script and the program are executable. I just don't know the optimal way to start them with sudo at startup.

Please be gentle. I'm a new user.

Best Answer

  • For command-line applications that do not require GUI, it is sufficient to place the call to them into /etc/rc.local , which already runs as root, thus does not need sudo. Below is example of my own /etc/rc.local which I use for starting two monitoring scripts.

    #!/bin/sh -e
    # rc.local
    # This script is executed at the end of each multiuser runlevel.
    # Make sure that the script will "exit 0" on success or any other
    # value on error.
    # In order to enable or disable this script just change the execution
    # bits.
    # By default this script does nothing.
    /home/xieerqi/bin/batmon.sh &
    /home/xieerqi/bin/sh/temperature.sh  &
     exit 0

    For GUI applications, you would need to take a different approach. You would need to open Startup Applications app, and add the following command:

    bash -c "sleep 10;gksu /usr/bin/my_vpn_program"

    What this does is gives GUI sufficient time to start, 10 seconds, then will bring up password dialog and if you enter password properly, will launch your command. Effectively this is a mini bash script. You can use pkexec instead, and some might even say pkexec is recommended instead of gksu.

    Alternatively, if you don't want to enter password every time, you can allow your user run this particular command with root privileges without authentication. For that you need to edit /etc/sudoers file. WARNING: it is recommended that you use sudo visudo to edit the file from terminal. Below is example of how I use the same setting with pm-suspend command:

    # Allow using pm-suspend for my user without password
    my_username_here ALL = NOPASSWD: /usr/sbin/pm-suspend

    This line should be appended to the end of /etc/sudoers file and saved. Note, that you still need to append sudo or gksu to the beginning of each command that you set up. Thus, you would need to use the same bash command I showed previously.

  • Related Question