Thursday, July 18, 2013

Execute Linux Commands from Browser

If you need to execute a shell command using browser here's how to do it. To understand this tutorial you need to have advanced level of understanding of Linux and PHP.

Please read comment for further explanation.
If you need to execute shell command such as ./my_shell_script.sh parameter from browser you need PHP script like this:
<?php
echo "<hr>";
// Determine user - usually web server name
// such as Apache ( on CentOS ) or www-data ( on Ubuntu )
echo exec('whoami');
echo "<br>";
// Determine folder
echo exec('pwd');
echo "<br>";
// Execute shell script named my_shell_script.sh
// assign one parameter with value John 
// and print the output in browser
exec('my_shell_script.sh John',$out);

echo "\n <pre style='background:aqua;overflow:auto;'>";
foreach ($out as $key => $value) {
    echo "Key: $key -&gt; Value: ".htmlspecialchars($value)."<br />\n";
}
echo"</pre> \n";
?>

File myscript.sh:
#!/bin/bash
echo "Good morning " $1
echo "How are you"

You need to assign permissions to myscript.sh like this as root. Shell script could be in the same folder as PHP script.
Here's how to set permissions:

touch my_shell_script.sh
chmod g+x my_shell_script.sh 
chmod u+x my_shell_script.sh 
chmod 775 my_shell_script.sh 
chown linux_username:apache  my_shell_script.sh 
ll -a | grep my_shell_script.sh
-rwxrwxr-x.  1 linux_username apache     36 Jul 18 23:03 my_shell_script.sh

You need to know that in SSH console you execute programs as root or under other Linux username but in browser you execute scripts as www-data or apache.

No comments:

Post a Comment