When I am trying to run shell script with exec and shell_exe nothing happens!
When I run with those command ls or whoami all work's.
What could it be?
Do you echo the output?
echo exec('ls');
Do you have safe_mode enabled?
phpinfo();
When yes: (from the manual)
Note: When safe mode is enabled, you can only execute files within the
safe_mode_exec_dir. For practical reasons, it is currently not allowed
to have .. components in the path to the executable.
Try to call exec with
exec('...pathtoyourbashscript...', $out, $return);
Then
echo $return;
If it shows 127 it´s likely that the path is wrong.
Also check the permissions. User 'nobody' is probably the apache user, which needs the rights to access and execute the script.
You can change the permissions by running
chmod 755 pathtouyourscript
This means something like 'I don't mind if other people read or run this file, but only I should be able to modify it'.
If you're using Apache, check to make sure that the Apache user has the required permissions to execute the php file.
You can use reflection to figure out if the function has been disabled with disable_functions.
$exec = new ReflectionFunction('exec');
print $exec->isDisabled() ? 'Disabled' : 'Enabled';
If the program is web based i.e. for linux, Try making a php file to process the shell.
and a shell file to handle the php..
For instance: runAllShell.php file can contain a loop.:
<?php
// Developed by A T.
// Count the files
$directory = '/put/directory/path_here/';
$files = glob($directory . '*.*');
if ( $files !== false )
{
$filecounter = count( $files );
}
else
{
echo "No Files were found";
}
$fileCount = $filecounter;
// Start the index
$fileNumber = 1;
while($fileNumber <= fileCount){
shell_exec('$fileNumber . ".sh"');
// get some feedback
echo "The ".$fileNumber." file has been excecuted";
// increment file number
$fileNumber++;
}
?>
make sure that all the .sh files in the directory are numericaly ordered for this to work i.e: 1.sh 2.sh 3.sh and so on.
Best regards,
AT.
Related
What I want to achive:
I want to update my git repository (which holds my laravel app) on my shared host whenever i push something into my repository. To do so, I have a deploy.sh script on my shared host which pulls my repository and deletes all caches from my laravel app.
In order to run this bash script automatically I also got a php script which is triggerd by a Github webhook whenever i push something into my repository.
My problem:
I try to run my bash script on my shared host with my php script but that doesn't work.
What i tried:
My bash script by itself runs perfectly fine when I execute it manually on my shared host via ssh. But it won't get executed by my php file.
PHP
<?php
function debug_to_console($data) {
$output = $data;
if (is_array($output))
$output = implode(',', $output);
echo "<script>console.log('Debug Objects: " . $output . "' );</script>";
}
$access_token = 'maxi9000';
$client_token = $_GET['token'];
if ($client_token !== $access_token)
{
echo 'error 403';
}
else{
$old = getcwd();
echo '</br>'.$old;
$file = $old.'/mhraschan.com/deploy.sh';
echo '</br>'.$file;
if(is_file($file)){
echo '</br>Is file';
if(!is_executable($file)) {
chmod($file, 0755);
echo '</br>file not executable - run chmod';
if(is_executable($file)) echo "File is now executable";
}
//Try to run bash file
$return = shell_exec('bash '. $file);
echo '</br>Shell return: '.$return;
debug_to_console('Shell return'.$return);
}
}
?>
Output of my browser when running the php script manually:
/data/web/e115665/html/test
/data/web/e115665/html/test/mhraschan.com/deploy.sh
Is file
file not executable - run chmod
Shell return:
So my file is not executable and runs chmod but after that it seems that it still is not executable because it doesn't run that line again: if(is_executable($file)) echo "File is now executable";
Also i dont get any output from my shell_exec command.
Any solution?
This is almost certainly an issue with permissions - remember, your web server is not running as root; if you're using Apache, you're probably running as www-data - other web servers will use other users. Thus, your attempt to chmod the file is failing, since you don't have permission to change the permissions on that file. And if the permissions for the file do not include "executable" for the web server's user, the script will not run.
Check the return value from the chmod function - I think you'll find it's false (meaning that it failed, per the documentation).
I am trying to convert a pdf file into text file. When I run the command through terminal its working fine but when try to execute it through PHP it's not working.
I am stuck in this situation from last four hour spend lots of time in google but no solution available. Can any body resolve this issue?
File owner - nobody
shell_exec('/usr/bin/pdftotext /opt/lampp/htdocs/foldername/filename.pdf');
Can anyone provide any helpful solution?
I also tried to change usr folder ownership from root to nobody and provide 777 permission on folder and its context.
Your command to run pdftotext is not correct.
There should be a second argument telling pdftotext to write to a specific file or just use a dash "-" to write to stdout, unless you actually want the program to create a text-file with the filename as the pdf (this would require write permissions in the /opt/lampp/.../ folder)
This is at least true for pdftotext version 0.12.4
"Pdftotext reads the PDF file, PDF-file, and writes a text file, text-file. If text-file is not specified, pdftotext converts file.pdf
to file.txt. If text-file is ´-', the text is sent to stdout."
So, the solution to your question would simply be add a dash after the filename, like so:
<?php
$pdftext = shell_exec('/usr/bin/pdftotext /opt/lampp/htdocs/foldername/filename.pdf -');
echo $pdftext;
Provided that the binary exists and PHP is allowed to use shell_exec and you have permissions and that the pdf-file exists and you have permissions.
from how to test if PHP system() function is allowed? and not turned off for security reasons
function isAvailable($func) {
if (ini_get('safe_mode')) return false;
$disabled = ini_get('disable_functions');
if ($disabled) {
$disabled = explode(',', $disabled);
$disabled = array_map('trim', $disabled);
return !in_array($func, $disabled);
}
return true;
}
You may need to check if isAvailable('shell_exec')
On shared hosting this function might be disabled.
If it's not disabled, check the Apache log, it's all you can do.
try exec and also make sure safe mode off in your php.ini file like this safe_mode = Off
exec('/usr/bin/pdftotext /opt/lampp/htdocs/foldername/filename.pdf')
also run this cmd in terminal to check if software is working
This is usually a function disabled by many webserver, you can check:
var_dump(ini_get('disable_functions')); // not available if shell_exec disabled
var_dump(ini_get('safe_mode')); // not available if true
Since You are running Linux you may have a rights Problem
Check your file is owned by apache.
chown apache apache file.php
Check youir file has rights
chmod 644 file.php
Maybe check your sudoers file aswell
Sudoers ManPage
I have the following PHP code:
<?php
$video = "C:\Users\Administrator\myVideo\processing\video.mp4";
$cmd = 'ffmpeg -i "' . $video .'" 2>&1 | wtee buffer.txt'; // wtee is a Windows version of tee
exec($cmd);
echo($cmd);
?>
If I run aa.php, which contains the above code, it won't work.
But if I run the $cmd that is being echoed out on the command prompt directly, the file buffer.txt is created and works.
I want to get the output of this:
$cmd = 'ffmpeg -i "' . $video .'"'
Into a variable like, e.g. $output.
This code, so far, prints blank:
exec($cmd,$output,$result);
print_r($output);
Like you mentioned, that your code works directly from command line but not from PHP CLI, is most likely because of log file permissions, which means, you must create a log file with correct permissions first, and then write your output there!
For example, from command line (not PHP) make sure that you delete your log file buffer.txt and run your PHP code again. Most likely it will not work as your file doesn't exist. Remember, when you run that command from command line directly, your log file, which is buffer.txt is created with special permissions (not only read/write, but also group and owner (Linux)). When PHP creates a file, by default, it uses nobody nobody for owner/group and you already have a log file (as you ran that same command from command line), which is created by other user (I suppose administrator), as a result you can be sure that PHP will not be able to use it, just because of the wrong file permissions. Try to see what is on your current log file owner/group by executing ls -ls in Linux or DIR /Q in Windows to get the idea.
Besides everything, make sure that you're not running PHP in safe mode, as a result exec might not work as you expect it, because it's disabled if PHP is in safe mode.
shell_exec() (functional equivalent of backticks)
This function is disabled when PHP is running in safe mode.
exec()
You can only execute executables within the safe_mode_exec_dir. For practical reasons it's currently not allowed to have components in the path to the executable. escapeshellcmd() is executed on the argument of this function.
You can check your server's PHP settings with the phpinfo() function.
Your code should rather look like this:
exec("$cmd 2>&1", $output);
log_conversion($config['logs_path']. '/' .$video_id. '_log.txt', $cmd);
log_conversion($config['logs_path']. '/' .$video_id. '_log.txt', implode("\n", $output));
What does that mean? If you say 2>&1 then you are redirecting stderr to wherever stdout is currently redirected to. If stdout is going to the console then stderr is, too. If stdout is going to a file then stderr is as well.
Please read more about command redirections in articles Using command redirection operators for Windows or All about redirection for Linux.
Your log conversion function, could be something like this:
function log_conversion($file_path, $text)
{
$file_dir = dirname($file_path);
if( !file_exists($file_dir) || !is_dir($file_dir) || !is_writable($file_dir) )
return false;
$write_mode = 'w';
if( file_exists($file_path) && is_file($file_path) && is_writable($file_path) )
$write_mode = 'a';
$handle = fopen($file_path, $write_mode);
if( !$handle )
return false;
if( fwrite($handle, $text. "\n") == FALSE )
return false;
#fclose($handle);
}
It's very important to make sure that the log file you create is writable and has correct permissions!
I personally delete the log file in case it exists, to make sure that I have recent and reasonable log file.
I bet it will work either like this or with small tweaking!
If it doesn't work for you, please let me know and I will elaborate!
exec requires an array for the output variable.
So try:
$output = array();
exec($cmd, $output, $result);
That will give you an array where each element is a line returned by your command.
Hey, I'm trying to use PHP to execute a shell command which will run remotely run a server on my box. Here is my PHP Code:
if ($key == "test") { echo "<font color='green'>Key is valid. Server satrted.</font>";
$start = system('cd /root/st/; ls;');
}
The problem is, the ls command runs from the same directory as the web server, which returns all of the files from /var/www/html instead of /root/st/. I have also tried the chdir command to no avail. Anyone know how you would get the directory to change so that the command could be run from a specified directory? Thanks.
Does the user that PHP is running as (eg, the user invoking the CLI script) have permission to read the directory? If you're going into /root/ but aren't root, you'd need to either add cd to sudoers for the current user, or choose another directory.
Edit: note that adding cd to sudoers is not even remotely okay for anything other than a local, you-only script. :)
There are two ways I would approach this.
1: use proper unix commands, and see if they work. IE:
if ($key == "test") { echo "<font color='green'>Key is valid. Server satrted.</font>";
$start = system('ls /root/st/');
}
2: Make it run a script on the system, that can go outside the webserver's chroot.
if ($key == "test") { echo "<font color='green'>Key is valid. Server satrted.</font>";
$start = system('server.sh');
}
and server.sh is
#!/bin/bash
cd /root/st
ls
PHP has a chdir() function. Not sure if it applies to exec/system calls, but worth a try.
Store the location in a variable, say $loc = '/root/st' and then do ls $loc in your code. Hope this helps.
Your problem is not the directory the script is running in (or more precisely the current working directory of the user running the script), but that cd /root/st/ will fail on any reasonable configured UNIX/Linux system. /root is usually owned by root and can't be accessed by any other user.
Using you snippet this will silently fail because you unconditionally chained the cd and the ls commands with a semicolon instead of &&.
I have a php script:
$extract_dir = "./";
$extract_file = "extractME.zip";
$zip = new ZipArchive;
$res = $zip->open($extract_file);
if ($res === TRUE) {
$zip->extractTo($extract_dir);
$zip->close();
echo "ok";
} else {
echo "failed";
}
But when I execute this script, via http://www.mywebsite.com/extract.php
All the files on FTP are show with OWNER 'root', but not the user ex . 'neo' as it should be. So the user cant edit/rename/delete these files.
Is it possible to fix this anyhow (I own the server), that files will be extracted with 'USERNAME' OWNERSHIP ?
ozzwanted, for some reason your web server (apache) is running as root so any file it makes will be made as root. This should never be the case. apache usually runs as 'www-data' or 'httpd', or 'nobody' or 'god' depending on the linux distro.
I suggest you look into this from a sysadmin point of view and have someone sort it out for you before you end up getting exploited. (assuming this is a live server)
You can use www.php.net/chown function or your can run a 'chown' command on the command line or do it from PHP with something like system() or exec() functions.
Good luck.
It extract as the user running the webserver (note: you should not be running it as root). Try using chown.