Running Shell Commands With Java As Root

For a long time I’ve been searching for running sudo commands without password prompt in Java. I’ve seen a post by Saeid Zebardast and thanks to him I solved that issue.

First you need  to edit /etc/sudoers file:

$ sudo gedit /etc/sudoers

and add that lines to this file:

# for user
YOUR_USER_NAME ALL= NOPASSWD: ALL

# for group
YOUR_GROUP_NAME ALL= NOPASSWD: ALL

Although the first line is worked for me, Saeid suggests adding both.

Anyway, after that change you can run your sudo command within Java:

String command = "sudo chmod 777 /home/gokceng/Desktop/test.my";
 Runtime runtime = Runtime.getRuntime();
 try
 {
 Process process = runtime.exec(command);
 BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
 String line;
 while ((line = bufferedReader.readLine()) != null)
 {
 System.out.println(line);
 }
 }
 catch (IOException e)
 {
 e.printStackTrace();
 }

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s