How to execute a shell script in PHP? - php

I have a script in /var/www/myscript.sh which creates folders and runs the command svn update for my projects. I need to execute this script by calling it in a PHP file in the browser (i.e. Localhost/test.php). I tried using functions shell_exec() and exec() but those did not work. I ran my shell script in terminal with su www-data && ./myscript.sh and it worked. What else am I missing?
<?php
$output = shell_exec("./myscript.sh");
?>
Update 5/4/2011:
I added www-data ALL=(ALL) NOPASSWD:ALL to /etc/sudoers and it works, but this is very insecure. Is there another way to do this?

Several possibilities:
You have safe mode enabled. That way, only exec() is working, and then only on executables in safe_mode_exec_dir
exec and shell_exec are disabled in php.ini
The path to the executable is wrong. If the script is in the same directory as the php file, try exec(dirname(__FILE__) . '/myscript.sh');

You might have disabled the exec privileges, most of the LAMP packages have those disabled. Check your php.ini for this line:
disable_functions = exec
And remove the exec, shell_exec entries if there are there.
Good Luck!

Residuum did provide a correct answer to how you should get shell exec to find your script, but in regards to security, there are a couple of points.
I would imagine you don't want your shell script to be in your web root, as it would be visible to anyone with web access to your server.
I would recommend moving the shell script to outside of the webroot
<?php
$tempFolder = '/tmp';
$webRootFolder = '/var/www';
$scriptName = 'myscript.sh';
$moveCommand = "mv $webRootFolder/$scriptName $tempFolder/$scriptName";
$output = shell_exec($moveCommand);
?>
In regards to the:
i added www-data ALL=(ALL) NOPASSWD:ALL to /etc/sudoers works
You can modify this to only cover the specific commands in your script which require sudo. Otherwise, if none of the commands in your sh script require sudo to execute, you don't need to do this at all anyway.
Try running the script as the apache user (use the su command to switch to the apache user) and if you are not prompted for sudo or given permission denied, etc, it'll be fine.
ie:
sudo su apache (or www-data)
cd /var/www
sh ./myscript
Also... what brought me here was that I wanted to run a multi line shell script using commands that are dynamically generated. I wanted all of my commands to run in the same shell, which won't happen using multiple calls to shell_exec(). The answer to that one is to do it like Jenkins - create your dynamically generated multi line of commands, put it in a variable, save it to a file in a temp folder, execute that file (using shell_exec in() php as Jenkins is Java), then do whatever you want with the output, and delete the temp file
... voila

If you are having a small script that you need to run (I simply needed to copy a file), I found it much easier to call the commands on the PHP script by calling
exec("sudo cp /tmp/testfile1 /var/www/html/testfile2");
and enabling such transaction by editing (or rather adding) a permitting line to the sudoers by first calling sudo visudo and adding the following line to the very end of it
www-data ALL=(ALL) NOPASSWD:/bin/cp /tmp/testfile1 /var/www/html/testfile2
All I wanted to do was to copy a file and I have been having problems with doing so because of the root password problem, and as you mentioned I did NOT want to expose the system to have no password for all root transactions.

Related

Issues With PHP exec & shell_exec - Shell Script Execution

I've been unable to run php scripts that I need to use to start and stop webcam services that run on the local machine with the scripts. I can find nothing in the logs to indicate why the script doesn't' work.
I confess to being severely handicapped regarding PHP, especially server-side scripting.
The environment is Debian Jesse running Nginx with all required SSH and PHP modules installed
I have added www-data to the sudoers file with:
www-data ALL=(ALL) NOPASSWD: /var/www/html/start_webcam.sh
Enabled the $PATH environment for www-data at:
/etc/php5/fpm/pool.d/www.conf
The shell script resides in the .../html directory and runs from the terminal with no issues.
This is the code for both the php and shell scripts:
start_webcam.php:
<?php
echo exec('sudo bash /var/www/html/aspirebox/start_webcam.sh 2>&1, $output');
print_r($output);
?>
The $output and print_r stuff is there because it was the last thing I tried based on a post I found out here somewhere.
start_webcam.sh
#!/bin/bash
service motion start
Thanks in advance to anyone out here that has a clue. After 2 days of wrestling with this, I am sure that I do not.
according to Passing Variables to shell_exec()? you should change your code like this:
<?php
$output = exec('/var/www/html/aspirebox/start_webcam.sh 2>&1 ');
print_r($output);
?>
and let your bash script execute as all (no need to sudo bash):
chmod a+x /var/www/html/aspirebox/start_webcam.sh
Thank you very much - that worked.
I worked through getting the path straight for the directory the shell script runs in, and the correct path to run "service".
All I have now is to figure out why I'm getting "Failed to start motion.service: Access denied"
I've given www-data permission to run the script without a password on sudoers, have to keep digging.
Thanks again!

Run PHP shell_exec() like root user

I building one PHP application where I create command line functionality for Linux debian Jessie. All works fne but I need to be able use some commands like root user.
Is there a way to use shell_exec() or similar command to access like root user via PHP?
Idea of this command line is to people who have access to that server can handle with it over internet from any place or device.
Here is image of console:
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
Edit your sudoers file
sudo vi /etc/sudoers
Put this line
www-data ALL=(ALL) NOPASSWD: ALL
www-data is the php default user in linux ( replace if necessary )
Use
$output = shell_exec('sudo XXXX');

Sudo in exec function

I have the following folder on my server, with the following files:
error-2015-12-20.log
error-2015-12-21.log
error-2015-12-22.log
And I written a PHP script that packs into .tar.gz with names earlier than the current date, moves the packed file into another partition, and removes the input files. It's done via exec().
The problem is that all of those operations require me to use sudo and provide password.
How can I deal with this?
Are you familiar with Linux file permissions?
If you want to execute a script you have to have the right to do so (by being in the group/owner with executable bit set), and if you want to read files you also have to have the right to read those files.
Otherwise you are forced to execute the file as sudo, because root can access all files.
Learn about this here: https://www.linux.com/learn/tutorials/309527-understanding-linux-file-permissions
As stated above it's a permission problem, to solve this let instruct sudo to let your php script run without prompting for a password:
Create a custom sudoers file :
sudo visudo -f /etc/sudoers.d/90_your_user
Copy the following contents in the newly created file (customizing the relevant section):
Cmnd_Alias PHP_SCRIPT = /path/to/my/script.php param1 param2
Cmnd_Alias ROOT_PROGS = PHP_SCRIPT
# Programs allowed to run without password prompt of your_user
your_user HOST=(root) NOPASSWD:ROOT_PROGS
You can then execute your program with sudo /path/to/my/myscript.php without permissions problem and without sudo prompts you for your password.

PHP executing external commands - how to when username and password required

Okay so I want to change the file mode of a directory to 777 so I use the line
exec('chmod -R 777' . $dir);
where $dir is the directory path of the directory I wanna change
it doesn't seem to work but I don't get an error for it, also if the user I was executing the script from was a sudo user so I have to enter the password after I enter the command, how would I do this? Would it be something like exec('chmod -R 777' . $dir\n 'password'); ?
Information I get from this site
Execute system commands via PHP
Many a times we need to execute system commands on a Linux system – to delete a directory, or restart a service. However, since Apache does not run with root privileges, it is nearly impossible to use PHP’s exec(), system() or passthru() functions to achieve that.
The solution to this is very simple, specially on Ubuntu. The Apache’s user www-data need to be granted privileges to execute certain applications using sudo.
1.Run the command sudo visudo
2.At the end of the file, add the following
www-data ALL=NOPASSWD: /sbin/iptables, /usr/bin/du
This is assuming that you wish to run iptables and du using super user (root) privileges. However, if you wish to run every application using super user privileges, then add the following instead of what’s above
www-data ALL=NOPASSWD: ALL
3.That’s it, now use exec() in the following manner inside your .php script
exec ("sudo iptables -P FORWARD ACCEPT");

sudo in php exec()

I don't know what the deal is here…
So I want to run an applescript: sudo osascript myscript.scpt
This works fine in the terminal, but not when I execute it via PHP's exec(); nothing happens. The console says
no tty present and no askpass program specified ; TTY=unknown ; …
I did my research, and it seems I'm missing the password for the sudo command. I tried a couple different ways to get around this, including:
writing %admin ALL=(ALL) ALL in /etc/sudoers
and proc_open() instead of exec()
none of which seem to be working, consequently driving me CrAzY!
So basically, is there a clear-cut way to get PHP to execute a simple terminal command?
EDIT: to clarify, myscript.scpt is a simple appleScript that changes the onscreen UI (for a larger project). In theory, simply osascript myscript.scpt should be enough, however the sudo is for some reason necessary to invoke some response from the system. If the sudo could be somehow eliminated, I don't think I would be having this permissions problem.
It sounds like you need to set up passwordless sudo. Try:
%admin ALL=(ALL) NOPASSWD: osascript myscript.scpt
Also comment out the following line (in /etc/sudoers via visudo), if it is there:
Defaults requiretty
I think you can bring specific access to user and command with visudo something like this:
nobody ALL = NOPASSWD: /path/to/osascript myscript.scpt
and with php:
#exec("sudo /path/to/osascript myscript.scpt ");
supposing nobody user is running apache.
php: the bash console is created, and it executes 1st script, which call sudo to the second one, see below:
$dev = $_GET['device'];
$cmd = '/bin/bash /home/www/start.bash '.$dev;
echo $cmd;
shell_exec($cmd);
/home/www/start.bash
#!/bin/bash
/usr/bin/sudo /home/www/myMount.bash $1
myMount.bash:
#!/bin/bash
function error_exit
{
echo "Wrong parameter" 1>&2
exit 1
}
..........
oc, you want to run script from root level without root privileges, to do that create and modify the /etc/sudoers.d/mount file:
www-data ALL=(ALL:ALL) NOPASSWD:/home/www/myMount.bash
dont forget to chmod:
sudo chmod 0440 /etc/sudoers.d/mount
I recently published a project that allows PHP to obtain and interact with a real Bash shell. Get it here: https://github.com/merlinthemagic/MTS
The shell has a pty (pseudo terminal device, same as you would have in i.e. a ssh session), and you can get the shell as root if desired. Not sure you need root to execute your script, but given you mention sudo it is likely.
After downloading you would simply use the following code:
$shell = \MTS\Factories::getDevices()->getLocalHost()->getShell('bash', true);
$return1 = $shell->exeCmd('/path/to/osascript myscript.scpt');
Run sudo visudo command then set -%sudo ALL=(ALL:ALL) to %sudo ALL=(ALL:ALL) NOPASSWD: ALL it will work.
I had a similar situation trying to exec() a backend command and also getting no tty present and no askpass program specified in the web server error log. Original (bad) code:
$output = array();
$return_var = 0;
exec('sudo my_command', $output, $return_var);
A bash wrapper solved this issue, such as:
$output = array();
$return_var = 0;
exec('sudo bash -c "my_command"', $output, $return_var);
Not sure if this will work in every case. Also, be sure to apply the appropriate quoting/escaping rules on my_command portion.
The best secure method is to use the crontab. ie Save all your commands in a database say, mysql table and create a cronjob to read these mysql entreis and execute via exec() or shell_exec(). Please read this link for more detailed information.
killProcess.php
I think directly calling a sudo command might be difficult because you are setting up the whole server to work without a password.
Perhaps as an alternative you could setup a CRONjob as root and monitor a flag file. Once the flag file exists it will run the osascript myscript.scpt and then delete the flag file.
This way you will keep SUDO secure from a config point of view and the server safer. To run the script you just need to touch the flag file from PHP.
It would of course introduce a delay of however many minutes you running the CRON job. It would also mean that you would have to redirect the output to a file and have a async monitor of the output, but it will depend on your application if this is a problem or not.
But it is an alternative that might protect the server.

Categories