Best view in Firefox and Chrome

How to execute SUDO shell command in PHP

Monday, May 25, 2009
Convert Article to PDFPrint ArticleEmail Article to FrinedBookmark this Article


Normally we can execute the shell commands through PHP. PHP have the inbuilt functions that can help us to execute the shell commands. The basic inbuilt functions are shell_exec('command_to_execute') and exec('command_to_execute'). Following example shows how we can list all the items in a specific directory in the server.


<?php $outPut = shell_exec("ls -al"); echo "<pre>$outPut</pre>"; ?>

Sometimes we need to execute some Super User ( SUDO)commands in shell commands through PHP. For that we need to use the pipeline to pass the password for that superuser. Have a look this line of codes. echo password_for_the_user | sudo -S command_to_execute Here we are passing the password in the pipeline. The '|' character is use to create the pipeline in shell scripts. Then when the shell scripe asked the password the echo statement will pass the password to the shell. Now we look at how we can do this in PHP.

<?php $outPut = shell_exec("echo password_for_the_user | sudo -S command_to_execute"); echo "<pre>$outPut</pre>"; ?>

Normally you wont get the output here.If you want to conform that it has no errors while executing the above lines, you can see the apache error log files in the which is inside the log folder. If it doesn't have any error message then its executed correctly. Note if you have any errors while executing these lines. Please go through the link bellow to understand the SUDO command in PHP and how it can apply in the Linux environment. SUDO shell command and sudoers file

Read these Articles :

2 comments:

Nimal said...

Really useful... and seem you finally figured it out... :)

Anonymous said...

Your code save main live ;] thx !!

Why Breeze

This is a new technological rhythm in the web. It blooms like a Breeze in your technological face with more than 75 technoligical atricles and guidences.

Contact Me
Contact Me Send an Email Facebook Account LinkedIn profile Twitter/Shayanth
Share And Save
Social Share with Twitter Facebook Share Add to Google Save on Delicious
Get Updates

The RSS will facilitate you to get the updates from Breeze. Click Here to redirect to the RSS link.

Designed by Posicionamiento Web | Bloggerized by GosuBlogger | Blue Business Blogger | Customized by SHAUOM