 |
shell_exec (PHP 4, PHP 5) shell_exec -- Execute command via shell and return the complete output as a string 说明string shell_exec ( string cmd )
This function is identical to the backtick operator.
参数
- cmd
The command that will be executed.
返回值
The output from the executed command.
范例
例子 1. A shell_exec() example
<?php $output = shell_exec('ls -lart'); echo "<pre>$output</pre>"; ?>
|
|
rustleb at hotmail dot com
05-Jun-2006 04:45
For capturing stdout and stderr, when you don't care about the intermediate files, I've had better results with . . .
<?php
function cmd_exec($cmd, &$stdout, &$stderr)
{
$outfile = tempnam(".", "cmd");
$errfile = tempnam(".", "cmd");
$descriptorspec = array(
0 => array("pipe", "r"),
1 => array("file", $outfile, "w"),
2 => array("file", $errfile, "w")
);
$proc = proc_open($cmd, $descriptorspec, $pipes);
if (!is_resource($proc)) return 255;
fclose($pipes[0]); //Don't really want to give any input
$exit = proc_close($proc);
$stdout = file($outfile);
$stderr = file($errfile);
unlink($outfile);
unlink($errfile);
return $exit;
}
?>
This isn't much different than a redirection, except it takes care of the temp files for you (you may need to change the directory from ".") and it blocks automatically due to the proc_close call. This mimics the shell_exec behavior, plus gets you stderr.
squeegee
05-May-2006 01:36
Each time you call shell_exec, it operates in a completely new shell. So if you need to do different multiple things in it based on whatever criteria, assemble your command ahead of time:
instead of
<?php
shell_exec("cd $path_to_dir");
shell_exec("ls -l");
?>
which, as you noted, won't work, do
<?php
$cmd = "cd $path_to_dir; ";
if($a == true)$cmd .= "ls -l";
else $cmd .= "du -h";
$result = shell_exec($cmd);
?>
notmespammers-iain at iaindooley dot com
19-Feb-2006 07:38
beware!
shell_exec('cd /path/to/dir');
shell_exec('ls -l');
will not give a listing of /path/to/dir!! use chdir() if you need to change directories, or group your commands with && (not always convenient/possible)
cheers
iain
rigsbr at yahoo dot com dot br
17-Feb-2006 10:24
If you need to execute a command without permission and could not execute it by ssh or install any extension, there is a way in Apache 1.3.x and PHP 4.
Create a file on cgi-bin directory, like this:
#!/usr/bin/php
<?
echo shell_exec('whoami');
?>
Don't forget to set the file you created the permission to execute it. Hence, call it from browser and you will se that this script will be executed by the shell user and not the user nobody (apache default user if running a PHP script).
andy25it at hotmail dot it
03-Jan-2006 01:06
As a webmaster i often deal with other servers with respect to the one that hosts my own site.
I actually had to face the following problem: some web pages depend directly from other webservers for example including a IMG SRC tag pointing to a remote image; but what if the remote server is temporary down? The download of the page remains in an incomplete state. It'd be better an error message for sure ! But how can i know whether the remote server is up or down? PING IT is the answer..but how can i use a shell system function that outputs only text into some PHP scripting?..here the solution:
<?php
/*
the host whose service status has to be checked out
*/
$host_to_ping = "www.somehost.net" ;
/*
I ping twice the host (a higher number of ping would only result the execute script time to be MUCH high).
The result of the output ping command is stored into a variable. This can be done beacuse of the properties and features of the shell_exec() function, see above to know more.
*/
$outputShell = shell_exec("ping -c2 -w2 $host_to_ping") ;
/*
Now the only thing i have to do is to look up the '0 received' string into the output to know whether the server is down or up.
*/
if(strpos($outputShell, '0 received')) {
#SERVER is DOWN so i include an error message
}
else {
#SERVER is UP so i include the normal code that is meant to be included by default
}
?>
I used the shell_exec() function for 2 reasons:
1) the system() function is disabled in my webserver by the hosting company for security reasons
2) the shell_exec() function returns a string containing the output of the shell command.
Regards to the community. Hope to have given a hand.
Andrea from Italy
Ashraf Kaabi
20-Dec-2005 02:06
I've write a Full Class for Run in Background, Kill PID , check if is Running
<?php
/**
* @author Ashraf M Kaabi
* @name Advance Linux Exec
*/
class exec {
/**
* Run Application in background
*
* @param unknown_type $Command
* @param unknown_type $Priority
* @return PID
*/
function background($Command, $Priority = 0){
if($Priority)
$PID = shell_exec("nohup nice -n $Priority $Command > /dev/null & echo $!");
else
$PID = shell_exec("nohup $Command > /dev/null & echo $!");
return($PID);
}
/**
* Check if the Application running !
*
* @param unknown_type $PID
* @return boolen
*/
function is_running($PID){
exec("ps $PID", $ProcessState);
return(count($ProcessState) >= 2);
}
/**
* Kill Application PID
*
* @param unknown_type $PID
* @return boolen
*/
function kill($PID){
if(exec::is_running($PID)){
exec("kill -KILL $PID");
return true;
}else return false;
}
};
?>
php [AT] jsomers [DOT] be
27-Sep-2005 09:00
<?php
/**
* PHP Kill Process
*
* Sometimes, it can happen a script keeps running when it shouldn't, and it
* won't stop after we close the browser, or shutdown the computer. Because it's
* not always easy to use SSH there's a workaround.
*
* @author Jensen Somers <php@jsomers.be>
* @version 1.0
*/
class KillAllProcesses {
/**
* Construct the class
*/
function killallprocesses() {
$this->listItems();
}
/**
* List all the items
*/
function listItems() {
/*
* PS Unix command to report process status
* -x Select processes without controlling ttys
*
* Output will look like:
* 16479 pts/13 S 0:00 -bash
* 21944 pts/13 R 0:00 ps -x
*
*/
$output = shell_exec('ps -x');
$this->output($output);
// Put each individual line into an array
$array = explode("\n", $output);
$this->doKill($array);
}
/**
* Print the process list
* @param string $output
*/
function output($output) {
print "<pre>".$output."</pre>";
}
/**
* Kill all the processes
* It should be possible to filter in this, but I won't do it now.
* @param array $array
*/
function doKill($array) {
/*
* Because the first line of our $output will look like
* PID TTY STAT TIME COMMAND
* we'll skip this one.
*/
for ($i = 1; $i < count($array); $i++) {
$id = substr($array[$i], 0, strpos($array[$i], ' ?'));
shell_exec('kill '.$id);
}
}
}
new KillAllProcesses();
?>
It's not the very best solution, but I've used it a couple of times when I needed to do it quick without to much trouble.
Make not I kill all the processes, on my server px -x will only return like 4 times /sbin/apache and it's pretty safe to kill them without any trouble.
concept at conceptonline dot hu
20-Sep-2005 05:02
Interestingly, if you execute a script which is not in your path (or you have made a typo, or if the script does no exist at all), you will get no return value. The error will be logged into the error_log of your webserver.
Someone could add a note how this can be (if it could be) overriden, as the standard behaviour is not really fool-proof.
ludvig dot ericson at gmail dot com
02-Sep-2005 02:50
(if you have any other way of doing this PLEASE send me a mail)
(The following note is interesting to *NIX administrators ONLY)
Jailing a PHP CLI session is not the easiest thing to do.
PHP has a gigantic list of dependencies, you can check it by
ldd `which php`
Each of these .so files (shared libraries) can have dependencies, and can depend on each other, making the list much bigger.
However, there are tools out there to copy all dependencies into a jailed directory, you just have to search for them - and I had no luck.
What I did was just to run these few commands:
su
mkdir /jailpath && mkdir /jailpath/lib
cp /lib/*.so* /jailpath/lib/
mkdir /jailpath/usr && mkdir /jailpath/usr/bin && mkdir /jailpath/usr/lib
cp /usr/lib/*.so* /jailpath/usr/lib
cp `which php` /jailpath/usr/bin
chmod -R 0755 /jailpath && chown -R root:root /jailpath && chmod 0000 /jailpath
Do note that this copies _all_ of your shared objects. There is one or two more libraries you have top copy, but chroot will tell you about which one it is.
Hope this helped somehow.
jesuse dot gonzalez at venalum dot com dot ve
15-Jul-2005 07:34
Here is an example of how you can execute a command in background an get the Process ID created by *NIX, for future reference or monitoring.
<?php
//Run linux command in background and return the PID created by the OS
function run_in_background($Command, $Priority = 0)
{
if($Priority)
$PID = shell_exec("nohup nice -n $Priority $Command > /dev/null & echo $!");
else
$PID = shell_exec("nohup $Command > /dev/null & echo $!");
return($PID);
}
?>
There is also a trick which I use to track if the background task is running using the returned PID
<?php
//Verifies if a process is running in linux
function is_process_running($PID)
{
exec("ps $PID", $ProcessState);
return(count($ProcessState) >= 2);
}
?>
I commonly use both functions in combination to batch copy big mysql tables in background and wait for the copy process to finish sending chunks to the client browser in the following way:
<?php
$CopyTaskPid = run_in_background("mysql --user=backup_user --password=backup_user_password --execute='INSERT INTO `backup-db`.`table` SELECT * FROM `online-db`.`table`'", "+20");
while(is_process_running($CopyTaskPid))
{
echo ".";
ob_flush(); flush();
sleep(2);
}
?>
joanacosta at prodigy dot net dot mx
25-May-2005 08:25
Here is another good example of how to Create a File with some variables already defined by user, and creating a file with them. of course using shell_exec
<?php
$generatefile = shell_exec("echo '$thisFOLIO','$thisREPORTO','$thisRESOLVIO','$thisVISTOB' > datosmanda.txt");
echo "<pre>$generatefile</pre>";
?>
Php Is Great.... cheers
dk at brightbyte dot de
14-May-2005 04:25
her's a function that is similar to shell_exec but captures both stdout and stderr. It's much more complicated than using 2>&1, but it's independent of the shell and should work on windows, too. It uses proc_open with stream_select and non-blocking streams to read stdout and stderr concurrently. It is not guarantied that the lines appear in the correct order or that they are not intermingeled - but it did not happened when I tested it. So, here goes:
<?php
function runExternal($cmd,&$code) {
$descriptorspec = array(
0 => array("pipe", "r"), // stdin is a pipe that the child will read from
1 => array("pipe", "w"), // stdout is a pipe that the child will write to
2 => array("pipe", "w") // stderr is a file to write to
);
$pipes= array();
$process = proc_open($cmd, $descriptorspec, $pipes);
$output= "";
if (!is_resource($process)) return false;
#close child's input imidiately
fclose($pipes[0]);
stream_set_blocking($pipes[1],false);
stream_set_blocking($pipes[2],false);
$todo= array($pipes[1],$pipes[2]);
while( true ) {
$read= array();
if( !feof($pipes[1]) ) $read[]= $pipes[1];
if( !feof($pipes[2]) ) $read[]= $pipes[2];
if (!$read) break;
$ready= stream_select($read, $write=NULL, $ex= NULL, 2);
if ($ready === false) {
break; #should never happen - something died
}
foreach ($read as $r) {
$s= fread($r,1024);
$output.= $s;
}
}
fclose($pipes[1]);
fclose($pipes[2]);
$code= proc_close($process);
return $output;
}
?>
here is how to use it:
<?php
$result= runExternal("ls -l some-file.txt",$code);
print "<pre>";
print $result;
print "</pre>\n";
print "<b>code: $code</b>\n";
?>
enjoy :-)
phillipberry at NOSPAM dot blisswebhosting dot com
11-Apr-2005 04:13
I found something odd.
If you run exec then straight after shell_exec the shell_exec will simply not run and will return NULL.
To get it to work i put a sleep(5) after the exec and now shell_exec works fine.
Kenneth
10-Mar-2005 01:19
Sometimes it's needed to be able to execute shell commands as root using PHP. For instance, restarting named after adding or changing zones, or adding new alliases for sendmail.
My approach is to run a server called Nanoweb, available from http://nanoweb.si.kz/. It's a webserver written in PHP, and needs only the pcntl extension extra to operate. Nanoweb is configured to only listen for connections on localhost, port 81 for example. From my normal PHP scripts running inside Apache I simply call scripts in Nanoweb to get the messy 'root' tasks done. Much more secure and safer.
Hope this helps
04-Jan-2005 01:10
Be careful as to how you elevate privileges to your php script. It's a good idea to use caution and planing. It is easy to open up huge security holes. Here are a couple of helpful hints I've gathered from experimentation and Unix documentation.
Things to think about:
1. If you are running php as an Apache module in Unix then every system command you run is run as user apache. This just makes sense.. Unix won't allow privileges to be elevated in this manner. If you need to run a system command with elevated privileges think through the problem carefully!
2. You are absolutely insane if you decide to run apache as root. You may as well kick yourself in the face. There is always a better way to do it.
3. If you decide to use a SUID it is best not to SUID a script. SUID is disabled for scripts on many flavors of Unix. SUID scripts open up security holes, so you don't always want to go this route even if it is an option. Write a simple binary and elevate the privileges of the binary as a SUID. In my own opinion it is a horrible idea to pass a system command through a SUID-- ie have the SUID accept the name of a command as a parameter. You may as well run Apache as root!
snoj-wwwposter at latitude dot li
30-Sep-2004 05:53
if the script you want to run from shell_exec needs more permissions than the webserver has (for example script needs root priviliges, do:
# chown root:root
# chmod 4711!
of course, replace root:root with the user that the script needs to run as and tweek the chmod for your security policy.
!! be careful about what the script does! remember it has root privilige!
James McCormack
06-Aug-2004 04:50
I had a perl program which ran fine from command line but not using shell_exec(), exec() or system() - nothing was being returned. I was using the full path and permissions were set correctly.
It turned out the perl program was using more memory than my PHP.INI file was set to allow. Increasing "memory_limit" solved the problem.
leaetherstrip at inbox dot ru
08-Jul-2004 05:23
Note on XP users: XP-Home edition does not allow to set rights directly on files and folders. You should use 'cacls' command-line utility to do this.
For example:
cacls c:\windows\system32\cmd.exe /E /G IUSR_ADMIN2003:F
gives IIS user full access to cmd.exe (potential security hole!), so PHP can fork and execute external programs.
vsuarez at vorealis dot com
01-Jul-2004 09:34
Got the error "Unable to execute..." when trying to run an external program with shell_exec under Windows XP, IIS 5, php 4.3.7 Solved by giving the IIS user (IUSR_...) execution privileges on the system file %systemroot%\system32\cmd.exe This should be used carefully because may represent a server's security hole.
dj-bj at gmx dot net
17-Mar-2004 09:22
shell_exec passes the result to a variable only if the result of the command is true.
When the result is false the generated page contains the error string in clear text at the position the result was fetched (which can differ from reload to reload).
If you would like to recieve also the error messages append 2>&1 to the end of the command you are executing.
However, the result is also passed to the page directly.
To avoid page destruction you should not fetch the result in your script.
By appending >nul to the shell command you can hide any output.
Hope this helps.
Martin Rampersad
11-Jan-2004 05:13
I have PHP (CGI) and Apache. I also shell_exec() shell scripts which use PHP CLI. This combination destroys the string value returned from the call. I get binary garbage. Shell scripts that start with #!/usr/bin/bash return their output properly.
A solution is to force a clean environment. PHP CLI no longer had the CGI environment variables to choke on.
<?php
// Binary garbage.
$ExhibitA = shell_exec('/home/www/myscript');
// Perfect.
$ExhibitB = shell_exec('env -i /home/www/myscript');
?>
-- start /home/www/myscript
#!/usr/local/bin/phpcli
<?php
echo("Output.\n");
?>
-- end /home/www/myscript
spagmoid at yahoo dot NOSPAMcom
18-Dec-2003 06:52
Note that whatever you run with this function seems to use PHP memory, so it will die if it exceeds the limit (usually 8 megs) To do database dumps or other memory-hogging operations use something like system() instead.
jessop <AT> bigfoot <DOT> com
04-Dec-2003 04:19
Just a quick reminder for those trying to use shell_exec on a unix-type platform and can't seem to get it to work. PHP executes as the web user on the system (generally www for Apache), so you need to make sure that the web user has rights to whatever files or directories that you are trying to use in the shell_exec command. Other wise, it won't appear to be doing anything.
ericphp at shepard dot com
23-Nov-2003 06:45
I had major problems getting sell_exec() to work from PHP. It was working fine via the Telnet command line.
Turns out (for me anyway) it was a pathing problem. I'm set up on a VPS FreeBSD server the does not (technically) have root access.
PHP needs to reference the FULL PATH to the app it's calling. But it gets more tricky than that. There may be more than one full path on a server. For instance, on mine there is:
>find ~/ -name mysqldump (VPS non-root search method)
/usr/local/bin/mysqldump
/usr/home/myusername/usr/local/bin/mysqldump
/usr/home/myusername/usr/local/mysql-3.23.41/bin/mysqldump
/usr/home/myusername/usr/local/mysql-3.23.43/bin/mysqldump
Turns out (after 5 hours of hair pulling fun) that /usr/home/myusername/usr/local/mysql-3.23.43/bin/mysqldump was the winner.
The same applies to using cURL and PHP via Cron. /usr/home/myusername/usr/local/curl-7.10.5/bin/curl works for me there.
And tar wouldn't work until I dug up PHPTAR /usr/home/myusername/usr/local/bin/phptar. Never new that existed ...
Good luck.
moneyboi at fuckwindows dot com
17-Jul-2003 09:46
shell_exec("yourscript.sh") is great for opening shell scripts.
eremi at eremi dot net
10-Jun-2003 01:29
To output the command has it should be, you can do the str_replace trick above, or you can put the output in a <pre> tag.
Example:
<?php
$output = shell_exec("[command]");
echo "<pre>$output</pre>";
?>
Ben
05-Jun-2003 01:01
When running subprocesses via shell_exec (and maybe others) from Apache/mod_php4, Apache's environment variables don't seem to be passed on to the subprocess environment unless you specifically force them by using putenv something like this:
$remaddr = getenv("REMOTE_ADDR");
putenv("REMOTE_ADDR=$remaddr");
shell_exec("/path/to/subprocess");
dan at mathjunkies.com
16-Apr-2003 12:02
Just a note for anybody who's box is involuntarily running in safemode (i.e. you buy space on a server), or just not working right. Shell commands won't work. You can, however, use PHPs FTP functions to FTP in. I was copying files and making directories, but I assume there might be a way to do something more complex.
mcbeth at broggs dot org
15-Apr-2003 05:18
As far as error checking on the last example. Several of the shells have the && operator, so you just string your commands together using it instead of ; If at any time any of the programs fail, you will return without running the rest
ron dot petty at unigeek dot com
22-Mar-2003 03:40
Here is an example on how to install software using php
shell_exec("cd /usr/local/src/; gunzip program.tar.gz; tar xvf program.tar; cd program; ./configure; make; make install);
Now depending if your root or not some commands like "make install" may fail. This doesn't do any error checking, the reason for that is I do not know how to cd to a directory and then execute another command unless they are in the same shell.
So basically, take what you type on the command line and string them together.
bruce at accumatics dot com
02-Feb-2003 01:24
If you're not getting any output from echo shellexec( "count.pl" ) [for instance], at least try "./count.pl" before bothering with the full path.
flame
30-Jan-2003 10:21
add '2>&1' to the end of your shell command to have STDERR returned as well as STDOUT.
$shell_return = shell_exec($shell_command." 2>&1");
ryon -at- ryon labaw -dot- com
17-Jan-2003 04:47
Note: You cant used shell_exec() when safemode = on (its disabled), instead use
exec() and copy the needed program into the /nonexec directory (by default, set in php.ini).
dj-bj at gmx dot net
17-Dec-2002 10:27
Running PHP 4.2.3 on Windows 2000 Server shell_exec works fine and passes its output to the variable when the result of the executed command is true.
However, if the command fails and the DOS-shell returns an error the result is no longer availiable in the variable but is passed directly to the page.
yaacov at pleasedontspamme dot spam
30-Oct-2002 02:46
If you're running scripts or commands and can't figure out what's not working, check to make sure that you're not using an alias in place of a command. PHP (quite reasonably) doesn't seem to recognise aliases.
php at chris-decker dot com
25-Jun-2002 02:12
I have found it easiest to use the following code to execute a shell command and return all of it's output (not just the last line) to the user as if he/she were sitting at the terminal:
$output = shell_exec("$command");
echo(nl2br($output));
matt_smith&uconn_edu
19-Jun-2002 12:51
Re: executing scripts that work on command line, but not from PHP system() calls -- Make sure you include the full path to the executable.
tonysb at gmx dot net
31-Mar-2002 04:57
shell_exec is extremely useful as a substitute for the virtual() function where unavailable (Microsoft IIS for example). All you have to do is remove the content type string sent in the header:
<?
$mstrng = shell_exec('yourcgiscript.cgi');
$mstrng = ereg_replace( "Content-type: text/html", "", $mstrng );
echo $mstrng;
?>
This works fine for me as a substitute for SSI or the virtual() func.
Anton Babadjanov
http://www.vbcn.com.ar
|  |