Monday, April 30, 2012

How to run sudo application on startup in Ubuntu without asking for password

Option 1 - Startup Applications


Step 1: Use Ubuntu UI for configuring Startup Applications. Depending on the Ubuntu version you can either go to System > Preferences > Startup Applications or type "Startup Applications" in Dash. From there you can simply edit the list of applications that you want to run on startup. More about Startup Application UI.

Step 2: Configure your application to start with sudo without asking for password. For that you need to add your application to the list of sudoers and disable  password just for your app. Let's open the sudoers configuration file. This can be done with visudo command like this:
sudo visudo

The reason visudo commend is recommended over using a regular text editor is because it locks sudoers configuration file while you are editing it.

Now let's say your user name is user1 and app name is my_app.jar, then add the following line to the configuration file:
user1 ALL=NOPASSWD: java -jar /usr/local/my_app.jar

All done. Now you can restart Ubuntu and enjoy your app running.

Option 2 - Add your app to rc.local


Option 1 will start your application only after user has logged in. What if need to start your application before that or regardless if user has logged in or not? The one of the simplest options is to add your application to the rc.local file. Open editor:
gksu gedit /etc/rc.local

And add your command to execute application just before the exit 0 statement.

Option 3 - Run your app as a Service


Most common approach in Linux world is to add your app to the /etc/init.d script. You can do the same in Ubuntu too, but Ubuntu has something even better. It's called Upstart. You can find the mode details on how it work in this blog post and on Ubuntu help page.

The beauty of this approach is that you can easily control your service from command like using start and stop command. It also allows you to configure dependencies on other services.

-=Oleg=-