I have a python script which is needed to be run by php:
<?php
$command = escapeshellcmd('/home/Desktop/test.py');
$output = shell_exec($command);
echo $output;
?>
The out put of the python script is a binary file but I get the following error in the log:
Unable to access the X Display, is $DISPLAY set properly?
The php code works fine from the terminal but no luck when I try to run it from the browser. Any idea what is going on? Ideally, I don't want to change my program. I want to know how you can rectify the X Display error. Is there a way to check if $DISPLAY is set properly? ( I am working with Ubuntu)
I tried this : pidof X && echo "yup X server is running" on my terminal and it is saying yup x server is running!
Add the following text as the first line of your Python script:
#!/usr/bin/python
Without this, the kernel doesn't know what interpreter to run your script with, and may end up trying to launch it using /usr/bin/import (because that word probably appears on the first line of the script). The import utility requires access to the X11 display (it's a screenshot utility, basically), which is why you're getting this error.
The python file you need may need to open a window to run. You say you saw it run in terminal though? What's test.py? Is it propitiatory?
If you try using this as a command in your PHP: (not 100% that the shell escape won't strip this so may need to comment that out)
python -c \'print \"Test\"\'
and see if you get the output text back. If so it's a python issue not PHP and the test.py file may be instantiating something that needs the $DISPLAY var set. PHP doesn't set the $DISPLAY var as it is shell commands not GUI.
try popen
$command = "/usr/bin/python /home/Desktop/test.py";
$handle = popen($command, "r");
"r" for read
$read = fread($handle, 10);
10 is the size of output you want to take,
echo $read ;
hope it helps,
Related
I have a python script that prints out the program names that are currently in the volume mixer in Windows 10.
This works fine when I run it in the cmd.
C:\wamp\www\Volume>py test.py
firefox.exe,Spotify.exe,Microsoft.Photos.exe,Steam.exe,
and here is my python script.
import sys
from pycaw.pycaw import AudioUtilities
def main():
list = ''
sessions = AudioUtilities.GetAllSessions()
for session in sessions:
volume = session.SimpleAudioVolume
if session.Process and session.Process.name():
list += session.Process.name() + ','
sys.stdout.write(list)
if __name__ == "__main__":
main()
And my PHP:
$python = "py";
$script = "test.py";
exec("$python $script 2>&1", $output);
print_r($output);
But when I run it in PHP using WAMP, I don't get any output from that script, nothing is outputted.
If I change my python script to only contain "print("TESTING")" then I can read that output fine in PHP which makes me think that my python code is failing perhaps due to permissions. So I changed the user from SYSTEM to my own user so when I use:
echo exec("whoami") // Outputs my user account name
I thought maybe my PHP script was off, so I tried running it though the command line, but the results are what I want:
C:\wamp\www\Volume>php index.php
Array
(
[0] => firefox.exe,Spotify.exe,Microsoft.Photos.exe,Steam.exe,
)
So I'm at a loss as to why when I execute my PHP code through my browser, I am not getting any output unless my python script only contains :
print("TESTING")
What could possibly be going wrong?
EDIT
So I decided to debug this further by altering my python script to create a .txt file on my desktop, this works fine when running it through the command line. But again, when I run it through my browser/PHP, that file isn't created. So maybe I need to grant special permissions to my python script? I'm not sure why I need to do that though as I have given PHP my user account
So I think I found out why I'm not getting any output from my python script, thanks to #Torxed.
It seems like when I run the Python script through WAMP/PHP it must run as a different user/environment which doesn't have any Audio.
This is odd however as I've set 'wampapache64' to run as my user account, even after a restart I'm still getting the same results.
I've even tried
runas /savecred /noprofile /user:<USER>
But that just returns the password prompt which I won't be able to fill out in PHP.
This project looks like a dead end for now.
I have a Python file which uses
raw_input()
to enter in a URL. I then scrape the website using BeautifulSoup and ask the user a few other questions based on thee data on the website (that I just scraped..)
I wish to convert this command-line tool into a web app.
How would I go about doing this?
shell_exec()
won't do what I want, because (as far as I know) can't input data from raw_input() through PHP..
You are looking for readline or stdin stream:
With php://stdin
$fp = fopen("php://stdin","r");
$line = rtrim(fgets($fp, 1024);
With readline:
$line = readline("Command: ");
I actually created a dnsTools script that would run a perl script similar to how it sounds like what you want to do. I used shell_exec here is an example of what I did
$ip=shell_exec('/usr/bin/perl ./dnstools.pl -ta -h'.$_POST["domain"].' -s#vnsc-lc.sys.gtei.net');
Then my script would just return the IP as a string.
Remember:
The output from the executed command or NULL if an error occurred or the command produces no output.
http://php.net/manual/en/function.shell-exec.php
Also, keep in mind the security issues using the command could pose if there is user input.
If shell_exec is turned off you could try using curl to run the command though the web and then still process the results.
I have created a small php script locally that runs a java application in command line. This java application continuously runs and never finishes. As it runs, it outputs command line text. Here is the code:
<?php
set_time_limit(0);
$command = "java -Xms124M -Xmx124M -jar myapp.jar";
$end = " 2>&1";
$in = $command . $end;
$out = exec($in);
var_dump($out);
?>
My problem is that the output is never printed because the app never stops running. Is there a way to get the php to print out each line that is returned as the app is running?
Hopefully I am making sense here (Let me know if I am not).
You might want to take a look at the passthru function and the popen function. These should return output as it occurs (although passthru might buffer the output).
One solution would be to launch your process as a background process and redirect output to a file. You could then read the output file in PHP, but you really shouldn't leave PHP running like that, especially since your java process is expected to never end. A better solution would be to use AJAX polling to have PHP return any recent updates to the output file every few seconds or something.
In a previous post, I was trying to update the encoding for a download file from php. One of the suggestions was to run the unix2dos command before sending the file to the user. This works great when I run the command on the linux box, but when I try and run the command from php I get nothing. Here is what I tried:
$cmd = "unix2dos -n $fullPath $downloadFile";
echo exec($cmd, $out, $retVal);
This displays nothing to the screen, $retVal is 0, and $out is an empty string.
echo system($cmd, $retVal);
This displays nothing to the screen, $retVal is 0.
echo shell_exec($cmd);
This displays nothing to the screen.
I have also tried escaping the command and it parameters like:
$cmd = escapeshellcmd($cmd);
and
$cmd = "unix2dos ". escapeshellarg("-n \"$fullPath\" \"$downloadFile\"");
Please let me know if you see something that I am doing wrong.
Thanks!
Edit: Here is some info that may be helpful.
unix2dos version: 2.2 (1995.03.31)
php version 5.2.9
Running in apache 2 on in Redhat Enterprise Linux 4
Have you considered a pure PHP solution?
<?php
$unixfile = file_get_content('/location/of/file/');
$dosfile= str_replace("\n", "\r\n", $unixfile );
file_put_contents('/location/of/file/', $dosfile);
?>
Something like that should do it, although untested :)
Shadi
See which user the PHP exec command is running as:
<?php system('whoami'); ?>
If this command fails then you likely do not have permission to use exec() or system(), so check your INI files. But be sure to check the correct ones! On Debian systems there are separate Apache and CLI INI files stored at /etc/php5/apache/php.ini and /etc/php5/cli/php.ini respectively. Sorry I do not know the locations for RedHat.
If the whoami command succeeds, make sure that the unix2dos command can be run by the user that is shown, and that the same user is allowed to make changes to the files in question by using chmod or chown.
Are you using the full path to unix2dos? Perhaps the executable is in your path for your shell but not in the path that PHP is using.
My implementation of unix2dos produces no output. If the return value is 0 then the command succeeded and your file has been updated.
The only other thing I see is the -n option which my version doesn't seem to have. You should probably check your man page to see what options it supports
unix2dos does not display the file it converts. Therefor you must display it yourself. A very basic way to do it could be :
$cmd = "unix2dos -n $fullPath $downloadFile";
echo exec($cmd, $out, $retVal);
include "$fullPath."/".$downloadFile;
Using include is pretty dirty but quick and easy. A cleaner way would be to use fopen and read the file then display it.
You'd better create a function that enclose all the operation : conversion + display so you'll have everything at hands.
But, If I were you, I'd prefer to not use exec at all and use FileIterator with a trim on every line so you will not have to care about the carriage return nor deal with a hazardous shell binding.
Not sure about your exact problem, but debugging suggestion:
Try first setting $cmd to ls. See if that works. Then try using /bin/ls (use the full path.)
If those don't work, then there might be a problem with your PHP configuration - there might be a safemode parameter or something which disallows the use of exec(), shell_exec(), or system() functions.
I got the source code from here.
http://www.sfr-fresh.com/linux/misc/unix2dos-2.2.src.tar.gz
I compiled it and then ran the tool. This was my output:
rascher#danish:~/unix2dos$ ./a.out -n 1.txt 2.txt
unix2dos: converting file 1.txt to file 2.txt in DOS format ...
I think the problem is this: the program writes all of its output to stderr, rather than stdout. If you look at the source code, you can see "fprintf(stderr, ...)"
As far as I know, PHP will only read the part of your program's output that is sent to STDOUT. So to overcome this, it seems like you have to redirect the output of your program (unix2dos uses stderr) to stdout. To do this, try something like:
$cmd = "unix2dos -n $fullPath $downloadFile 2>&1"
The "2>" means "redirect stderr" and "&1" means "to stdout".
In either case, I would imagine that the file was converting properly, but since you weren't getting any of the expected output, you thought it was failing. Before making the change, check on the output file to see if it is in DOS or UNIX format.
Specifically I have a PHP command-line script that at a certain point requires input from the user. I would like to be able to execute an external editor (such as vi), and wait for the editor to finish execution before resuming the script.
My basic idea was to use a temporary file to do the editing in, and to retrieve the contents of the file afterwards. Something along the lines of:
$filename = '/tmp/script_' . time() . '.tmp';
get_user_input ($filename);
$input = file_get_contents ($filename);
unlink ($filename);
I suspect that this isn't possible from a PHP command-line script, however I'm hoping that there's some sort of shell scripting trick that can be employed to achieve the same effect.
Suggestions for how this can be achieved in other scripting languages are also more than welcome.
You can redirect the editor's output to the terminal:
system("vim > `tty`");
I just tried this and it works fine in windows, so you can probably replicate with vi or whatever app you want on Linux.
The key is that exec() hangs the php process while notepad (in this case) is running.
<?php
exec('notepad c:\test');
echo file_get_contents('c:\test');
?>
$ php -r test.php
Edit: As your attempt shows and bstark pointed out, my notepad test fires up a new window so all is fine, but any editor that runs in console mode fails because it has no terminal to attach to.
That being said, I tried on a Linux box with exec('nano test'); echo file_get_contents('test'); and it doesn't fail as badly as vi, it just runs without displaying anything. I could type some stuff, press "ctrl-X, y" to close and save the file, and then the php script continued and displayed what I had written. Anyway.. I found the proper solution, so new answer coming in.
I don't know if it's at all possible to connect vi to the terminal php is running on, but the quick and easy solution is not to use a screen editor on the same terminal.
You can either use a line editor such as ed (you probably don't want that) or open a new window, like system("xterm -e vi") (replace xterm with the name of your terminal app).
Edited to add: In perl, system("vi") just works, because perl doesn't do the kind of fancy pipelining/buffering php does.
So it seems your idea of writing a file lead us to try crazy things while there is an easy solution :)
<?php
$out = fopen('php://stdout', 'w+');
$in = fopen('php://stdin', 'r+');
fwrite($out, "foo?\n");
$var = fread($in, 1024);
echo strtoupper($var);
The fread() call will hang the php process until it receives something (1024 bytes or end of line I think), producing this :
$ php test.php
foo?
bar <= my input
BAR
system('vi');
http://www.php.net/system