简体   繁体   中英

Unable to execute bash script and programs through apache2 using php?

I have two PCs connected to each other as shown

PC1<==============>PC2

PC2 has apache2 running and has two executable python program files as python1.py and python2.py

I want a php script be created which would generate a simple web page with two buttons button1 and button2 . When button1 is clicked python1.py should execute on PC2 and if button2 is clicked than python2.py SO THAT THEY DISPLAY DATA ON PC2 ITSELF and do not send output to PC1.

I began with creating following basic script which successfully ran commands like 'ls' etc and successfully it ran those commands and displayed results at PC1 as a test ,

I have following issues :

1)HOw to run commands on PC2 and get data displayed on its own terminal? 2)I am not able to execute individual commands like 'firefox' as it does not give any error but doesnt launch firefox either..hence how do i execute python files ?

<?php
$output = shell_exec('ls -lart');
echo "<pre>$output</pre>";
?>

Above worked but when i modified it to something like below id doesn't work :

<?php
shell_exec('firefox');
?>

or

<?php
shell_exec('/var/www/html/test.sh');
?>

wherein ./test.sh is made executable and has :

#!/bin/bash
firefox

If i individually run above bash script , it launches firefox. I want this be done remotely on press of a button on a web page .

I tried this code :

<?php
echo exec('/usr/bin/firefox');

?>

and it gives :

root@astitva-Vostro-3446:/var/www/html# ./page1.php 
./page1.php: line 2: ?php: No such file or directory
./page1.php: line 3: syntax error near unexpected token `('
./page1.php: line 3: `echo exec('/usr/bin/firefox');'

And just because firefox is GUI hence tried following :

<?php
echo exec('/var/www/html/test.sh');

?>

and it gives :

root@astitva-Vostro-3446:/var/www/html# ./page1.php 
./page1.php: line 2: ?php: No such file or directory
./page1.php: line 3: syntax error near unexpected token `('
./page1.php: line 3: `echo exec('/var/www/html/test.sh');'

You are not executing page1.php as a PHP script. Without a shebang line (eg #!/usr/bin/env bash ) a script cannot be interpreted properly. Those errors you're receiving are appearing because bash is trying to interpret your file, not PHP. You have two options:

  1. Put a shebang line at the beginning of your scripts: #!/usr/bin/env php
  2. Execute the files with the PHP cli: php ./page1.php

I suggest #2 if you're also going to use the scripts through apache, nginx, etc. Otherwise #1 makes more sense.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM