Why doesn't exec("top"); work on Linux? - php

I was trying to execute this command
echo exec("top");
and
echo exec("/usr/bin/top");
neither works (returns blank output)
does anybody know why?

Because top is an interactive program that is meant to be run on a terminal, not be executed from a script. You are probably want to run the 'ps' command with arguments which will sort output by cpu utilization.
http://www.devdaily.com/linux/unix-linux-process-memory-sort-ps-command-cpu

You actually can call top and echo its output. Code that worked for me:
passthru('/usr/bin/top -b -n 1');
-b - running in batch mode
-n 1 - only one iteration

It probably works, but exec() doesn't return anything. Read the Manual: exec()
$output = null;
exec('top', $output);
echo $output;
But you have another problem: top doesn't exit by itself. You cannot use it here, because you need to send the interrupt-signal (just realized: q is ok too).
One solution is to make top to stop after one iteration
$output = null;
exec('top -n 1', $output);
var_dump($output);

If you want to put it in a variable :
ob_start();
passthru('/usr/bin/top -b -n 1');
$output = ob_get_clean();
ob_clean();

I used:
$cpu = preg_split('/[\s]+/', shell_exec('mpstat 1 1'));
$cpu = 100-$cpu[42];
100% minus the idle time.

Related

How to execute two CMD queries in PHP simultaneously

$command1 = "interfacename -S ipaddress -N nms -P company ";
$command2 = "list search clientclass hardwareaddress Mac address ";
if ( exec( $command1 . "&&" . $command2 ) ) {
echo "successfuly executed";
} else {
echo "Not successfuly executed";
}
If command 1 (cmd query) successfully executed, I want command 2 (which also contains some cmd queries) to be executed next. In the above script, only command 1 is executed. It doesn’t show any result for command 2.
I have wasted two days on this without finding any solution.
You can use either a ; or a && to separate the comands. The ; runs both commands unconditionally. If the first one fails, the second one still runs. Using && makes the second command depend on the first. If the first command fails, the second will NOT run. Reference
You can use shell_exec() PHP function to run Shell Command directly in your script.
Syntax : string shell_exec (string $cmd)
Example :
$output = shell_exec('ls -lart');
var_dump($output); #Showing the outputs
You can use multiple conditions in a single command line.
Example :
$data = "rm a.txt && echo \"Deleted\"";
$output = exec($data);
var_dump($output);
if($output=="Deleted"){
#Successful
}
In above example "Deleted" string will assign to $output when the file deleted successfully. Otherwise the error/warning/empty string will assign to $output variable. You should make condition with $output string.
Here is the documentation of shell_exec()
Note : There will be a new line character of the function shell_exec() output.
If I understand your question correctly, you want to execute $command1 and then execute $command2 only if $command1 succeeds.
The way you tried, by joining the commands with && is the correct way in a shell script (and it works even with the PHP function exec()). But, because your script is written in PHP, let's do it in the PHP way (in fact, it's the same way but we let PHP do the logical AND operation).
Use the PHP function exec() to run each command and pass three arguments to it. The second argument ($output, passed by reference) is an array variable. exec() appends to it the output of the command. The third argument ($return_var, also passed by reference) is a variable that is set by exec() with the exit code of the executed command.
The convention on Linux/Unix programs is to return 0 exit code for success and a (one byte) positive value (1..255) for errors. Also, the && operator on the Linux shell knows that 0 is success and a non-zero value is an error.
Now, the PHP code:
$command1 = "ipcli -S 192.168.4.2 -N nms -P nmsworldcall ";
$command2 = "list search clientclassentry hardwareaddress 00:0E:09:00:00:01";
// Run the first command
$out1 = array();
$code1 = 0;
exec($command1, $out1, $code1);
// Run the second command only if the first command succeeded
$out2 = array();
$code2 = 0;
if ($code1 == 0) {
exec($command2, $out2, $code2);
}
// Output the outcome
if ($code1 == 0) {
if ($code2 == 0) {
echo("Both commands succeeded.\n");
} else {
echo("The first command succeeded, the second command failed.\n");
}
} else {
echo("The first command failed, the second command was skipped.\n");
}
After the code ends, $code1 and $code2 contain the exit codes of the two commands; if $code1 is not zero then the first command failed and $code2 is zero but the second command was not executed.
$out1 and $out2 are arrays that contain the output of the two commands, split on lines.
I'm not sure to know about simultaneous execution but I'm sure about one cmd dependent on another cmd execution action. Here I'm running single execution cmd first to clear all set path, second I've declared my file path, third I install angular cmd npm install.
$path = "D:/xampp/htdocs/tests/omni-files-upload/aa-test/src";
$command_one = "cd /";
$command_two = "cd ".$path;
$command_three = "npm install";
#exec($command_one."&& ".$command_two."&& ".$command_three);

Executing python commands from php script

I have installed SymPi in the server and from the command line, I am able to execute the following.
python ./sympy-0.7.5/bin/isympy
(this will open a console where I can type mathematical expressions. then the following expression)
1 + 2
(will give 3 as output)
My aim is to do the same from php using shell_exec. I have written a php file as given below, but is not working.
$command = escapeshellcmd('python ./sympy-0.7.5/bin/isympy');
shell_exec($command);
$output = shell_exec('1 + 2');
Can anybody help me to figure out why this is not working?
Please note that the following script works fine which just execute a python script and retrieve the output.
$command = escapeshellcmd('python C:\PythonPrograms\test3.py');
$output = shell_exec($command);
echo $output;
My guess is that the working directory (cwd) of shell_exec is different from the one you're in when you execute it manually.
Your working example specifies a hard path that will work from anywhere. Whereas your not-working example specifies a relative path (./ is the cwd).
Convert your call to isympy to give its full path on disk. Or figure out how to set the cwd of shell_exec.
(If this doesn't solve it, say more than "is not working." What happens? An error? What is the full text of the error?)
Each time you run shell_exec, it opens a completely new instance of the shell.
Edit:
You can pass a command for python to execute like this:
$expression = '1 + 2';
$cmd = 'python -c \'print "%f" % (' . $expression . ')\'';
$output = shell_exec($cmd);
This, admittedly is not using sympy, but for simple mathmatical expressions you may not need to. If you do, you would just need to import the library in the same command, like this: python -c 'import sympy; print "%f" % sympy.sqrt(3)'
I could manage the desired result in a different way.
Created a python script which accepts the expression as the command line argument , execute and display the output.
Call this script from php by passing the expression as the command line argument.

Running at from PHP gives no output

I've been wrestling with exec(), trying to capture the output from it when I add a task using the at Unix system command. My problem is that it is giving no output when run from my script, however running it from the terminal and PHP in interactive mode prints out a couple of lines.
The command I want to execute is this:
echo exec("echo 'php -f /path/to/file.php foo=1' | at now + 1 minutes", $result);
var_dump() gives string(0) "", and print_r() spits out Array (). I've tried using shell_exec(), which outputs NULL, however the following outputs hi when run in a web page context:
echo exec("echo 'hi'");
This also outputs stuff:
echo exec("atq");
However, as soon as I use at, nothing is output. How can I get the output of:
exec("echo 'php -f /path/to/file.php foo=1' | at now + 1 minutes", $result);
Because at present it outputs nothing when run as "normal" by PHP through Apache, however running the command in the terminal as well as in PHP's interactive console gives me the expected result of something like:
php > echo exec("echo 'php -f /path/to/file.php foo=1' | at now + 1 minutes", $result);
warning: commands will be executed using /bin/sh
job 1219 at Sun Jun 10 12:43:00 2012
safe_mode is off, and I cannot work out why I don't get any output from at with a piped-in echo statement, when executing atq or any other commend with exec() gives me output. I've searched and read this question, all to no avail.
How can I get exec() to return the output from at to either a string, or an array if using a second argument with exec()?
Working, one line solution
I didn't realise it could be this simple. All that is required is to reroute stderr to stdout by putting 2>&1 at the end of the command to execute. Now any output from at is printed to stdout, therefore captured by exec():
echo exec("echo 'php -f /path/to/file.php foo=1' | at now + 1 minutes 2>&1", $result);
My old solution:
I was trying to keep to a one/two line solution, however the only thing that worked in the end was using proc_open() because at logs to stderr, which exec() doesn't read! I'd like to thank #Tourniquet for pointing this out, however he has deleted his answer. To quote:
As far as i can see, at outputs to stderr, which isn't captured by
exec. I'm not really confident in it, but consider using
http://php.net/manual/en/function.proc-open.php, which allows you to
direct stderr to its own pipe.
This is actually the correct way of doing things. My solution (because I only want stderr) was to do this:
// Open process to run `at` command
$process = proc_open("echo 'php -f /path/to/file.php foo=1' | at now + 1 minutes", array(2 => array("pipe", "w")), $pipes);
// Get stuff from stderr, because `at` prints out there for some odd reason
if(is_resource($process)) {
$output = stream_get_contents($pipes[2], 100);
fclose($pipes[2]);
$return_value = proc_close($process);
}
$output now contains whatever at printed to stderr (which should really go to stdout because it's not an error), and $return_value contains 0 on success.
Here a more complex solution with proc_open. I'm writing this answer because, in my case, the '2>&1' workaround doesn't work.
function runCommand($bin, $command = '', $force = true)
{
$stream = null;
$bin .= $force ? ' 2>&1' : '';
$descriptorSpec = array
(
0 => array('pipe', 'r'),
1 => array('pipe', 'w')
);
$process = proc_open($bin, $descriptorSpec, $pipes);
if (is_resource($process))
{
fwrite($pipes[0], $command);
fclose($pipes[0]);
$stream = stream_get_contents($pipes[1]);
fclose($pipes[1]);
proc_close($process);
}
return $stream;
}
Usage examples:
// getting the mime type of a supplied file
echo runCommand('file -bi ' . escapeshellarg($file));
Another example using the command parameter:
// executing php code on the fly
echo runCommand('/usr/bin/php', '<?php echo "hello world!"; ?>');
Another example using the force parameter (this can be useful for commands that will change the output during the execution process):
// converting an mp3 to a wav file
echo runCommand('lame --decode ' . escapeshellarg($source) . ' ' . escapeshellarg($dest), '', true);
I hope this helps :-)
Try to create a minimum (non-)working example. Break everything down, and test only one thing at a time.
Here is one error in your bash:
hpek#melda:~/temp$ echo 'php -f /path/to/file.php foo=1' | at now + 1 minutes
at: pluralization is wrong
job 22 at Sun Jun 10 14:48:00 2012
hpek#melda:~/temp$
Write minute instead og minutes.
My output from at is send to me by mail!!

how to prevent system() function from printing output in the browser?

I'm using system() PHP function to run some curl commands like this system("curl command here",$output); but it displays results on screen. Any way to avoid this output?
You're using the wrong function for that. According to the docs:
system() is just like the C version of the function in that it executes the given command and outputs the result.
So it always outputs. Use exec­Docs instead which does return (and not output) the programs output:
$last = exec("curl command here", $output, $status);
$output = implode("\n", $output);
Or (just for completeness) use output buffering­Docs:
ob_start();
system("curl command here", $status);
$output = ob_get_clean();
You coud try using output buffering.
ob_start();
system("curl command here",$output);
$result = ob_get_contents();
ob_end_clean();
You could either modify the command string and append " 1>/dev/null 2>&1" or - more elegantly - execute the process with a pipe (see example #2).
For a more refined control over the process' file handles, you can also use proc_open().
The system function displays the output from your command, so you're out of luck there.
What you want is to change system for exec. That function will not display the command's output.
No, you should use PHP curl library

How do I pipe rake output using php?

I'm building a RAKEFILE and I want to display the output on a php generated page as it gets executed.
I tried using system() since the PHP docs mention this:
The system() call also tries to automatically flush the web server's output buffer after each line of output if PHP is running as a server module.
This seems to work with multiple shell comands but when I execute rake I only get the first line:
(in /Users/path/to/proj)
Any ideas?
Cheers!
Try use exec() function
exec($command, $output);
$output is an array
//retrieved data
for($out = '',$x = 0,$len = count($output); $x < $len; $x++) {
$out .= $output[$x] . "\r\n";
}
or simple:
$out = join("\r\n", $output);
The system() call also tries to automatically flush the web server's output buffer after > each line of output if PHP is running as a server module.
This means you would only get the last line of output from the return value. The example in the system() manual page shows that and it suggests to use passthru() to get raw output. I usually use exec() though.
Turs out both functions system() & exec() actually work. The generated rake output when using --verbose isn't taken into consideration though. That's why I was confused. If anyone has more extensive knowledge on the distinction, do share :)

Categories