Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

executing python in the command line inside a controller - PHP/CodeIgniter

Inside my automation.php controller, I have the following function:

public function deploy_test() {

      echo json_encode(system("python --version"));
 }

When the user wants to deploy a test, by clicking a test button in the webpage, he would be able to accomplish such a task. However, when I click the test button, my output is:

""

Meanwhile, when I execute the same function with the command:

public function deploy_test() {

    echo json_encode(system("ls -l"));
}

I'm getting:

total 32
drwxr-xr-x. 15 philippe philippe 4096 Mar  4 16:48 application
drwxrwxr-x.  2 philippe philippe 4096 Mar  4 17:28 css
-rw-r--r--.  1 philippe philippe 6357 Jan 30 11:53 index.php
drwxrwxr-x.  2 philippe philippe 4096 Feb 27 15:38 js
-rw-r--r--.  1 philippe philippe 2496 Jan 30 11:53 license.txt
drwxr-xr-x.  8 philippe philippe 4096 Jan 30 11:53 system
drwxr-xr-x. 12 philippe philippe 4096 Jan 30 11:53 user_guide

Could someone please help me to get that straighten out?

like image 649
cybertextron Avatar asked Mar 05 '13 01:03

cybertextron


2 Answers

The problem is not with your code or PHP.

The problem is with your permissions.

php uses permissions which are set in the env-vars of apache.

Which is ideally set as :

User ${APACHE_RUN_USER}
Group ${APACHE_RUN_GROUP}

under your apache2 / httpd conf file.

For example:

Try running:

<?= `whoami` ?>

via your shell and via your browser.

Your browser will probably say www-data and shell will say your username or if you are on AWS - default, you would get root

You do not have to use system() , use exec() instead.

We should be close as :

echo json_encode(exec("python --version"));

Performing operations will require you to have correct User and Groups set.

Look up for : In the shell, what does " 2>&1 " mean?

So your code should be :

echo json_encode(exec("python --version 2>&1"));

Hope it helps!

like image 190
Kautil Avatar answered Sep 21 '22 15:09

Kautil


This works fine for my production server

public function deploy_test() {
    echo json_encode(system("python --version 2>&1"));
}

with the output

Python 2.7.3
"Python 2.7.3"

Output of the unix command printed twice as system() itself outputs the result to browser. So exec() can be used in the place of system to avoid this.

public function deploy_test() {
    echo json_encode(exec("python --version 2>&1"));
}

which outputs

"Python 2.7.3"

as expected.

like image 43
Cyril Avatar answered Sep 22 '22 15:09

Cyril