PHP sudo in shell_exec
You could use the latest SVN version of phpseclib, a pure PHP SSH implementation, to do this. eg.
<?php
include('Net/SSH2.php');
$ssh = new Net_SSH2('www.domain.tld');
$ssh->login('username', 'password');
$ssh->read('[prompt]');
$ssh->write("sudo command\n");
$ssh->read('Password:');
$ssh->write("Password\n");
echo $ssh->read('[prompt]');
?>
Run PHP shell_exec() like root user
Executing commands as root via PHP will leave yourself wide open to all sorts of malicious hackery.
Have a look at the "sudo" documentation.
You should be able to set up all the commands you need as "sudo"able scripts. It is much better to write specific scripts with limited functions than to expose the underlying priviledged command.
As in:
exec ('sudo getCurrentUser.sh')
First, you need to add the user that PHP is using to run (most of the time it is www-data
) to the sudo group if it is not already assigned.
Then, in your php file:
use sudo -S, so you can pass the password via echo
$exec = "echo your_passwd | /usr/bin/sudo -S your command";
exec($exec,$out,$rcode);
if you have trouble with the paths - use
"bash -lc 'echo your_passwd | /usr/bin/sudo -S your command'"
so you get a new bash that acts like a login shell and has the paths set
Related Topics
PHP Date Time Current Time Add Minutes
"Class Xxx Is Not a Valid Entity or Mapped Super Class" After Moving the Class in the Filesystem
How to Tell If a Timezone Observes Daylight Saving at Any Time of the Year
What Is a Good Method to Sanitize the Whole $_Post Array in PHP
Swift_Transportexception Connection Could Not Be Established with Host Smtp.Gmail.Com
Upload Images on Twitter Using PHP
Selecting All Fields Except Only One Field in MySQL
Targeting Specific Email with the Email Id in Woocommerce
Fatal Error: Class 'Mongodb\Driver\Manager' Not Found
Saving Habtm with Extra Fields
Base Table or View Not Found: 1146 Table Laravel 5
Remotely Connecting to a MySQL Database
Write a Text File and Force to Download with PHP
Laravel Cannot Delete or Update a Parent Row: a Foreign Key Constraint Fails
Adding Multiple Tabs to Woocommerce Single Product Pages