Python part of script does not start from webpage - php

I have a webpage on a linux NAS, with webserver and php running.
I want to start a script from de server, to write data to a database.
When i am on the new69.php (the website in question)
I have the
for example :
$uptime = exec('uptime');echo $uptime;
(and this works)
So i have a connection.
Then i do with a if statement:
if (isset($_POST['verzenden'])) {
$output1 = exec('whoami');
exec('/share/MD0_DATA/Qweb/sqlite/AllesNaardDB.sh');
} else {
echo "Nog lekker niets gedaan.";
Whoami in the is statememt gives the username "httpdusr",
So the if statement gets reached and works.
Now the exec statement when i do:
It has to execute the AllesNaardDB.sh
which contains:
cd /share/MD0_DATA/Qweb/sqlite
echo "Wasmachine"
python2.6 wasm_util_sql.py [param]
echo "alles gegeven"
exit 0
Nothing is shown or done.
But when i do:
$output = exec('/share/MD0_DATA/Qweb/AllesNaardDB.sh');
echo "<pre> $output </pre>";
I get the als line of the script in the variable $output,
"alles gegeven".
At first i tought that it could be something to do with the rights.
So i (switched user with) su to "httpdusr" and script in putty gets executed fine.
I also made another script ff.sh with "ls -l" to execute and everything works.
Also i treid
passthru(),
system(),
shell_exec.
The only improvements are that with system() and passthru(), the "echo "Wasmachine""
appeared on te website.
I don't get why the python jobs don't get started ?
I worked a little further, but could it be that there are some sqlite3 command which are user dependent ?
Like that i could execute some write action to the database as admin, but not as the httpdusr ?

try adding #!/bin/sh to the top of the script and make sure it's chmod a+x.

It is a prblem with a path in the python script, which is writing to the database.
It uses a different path when it is started from the webpage (MD0_DATA/Qweb/) then wen it is started from the shell script (MD0_DATA/Qweb/sqlite)
*i dit not solvend the problem yet, but understand it.
Everybody thanks for the effort.

Related

PHP execute SSH2 command

I'm having some problems with PHP SSH2 commands.
So I have succesfully connected my dedicated server with my app, but I have no idea how to run command with that.
I'm using phpsclib ( http://phpseclib.sourceforge.net ), when I write something like
echo $ssh->read('username#username:~$');
$ssh->write("ls -la\n");
echo $ssh->read();
It will give me a list from root, but the problem is I don't want to be in root.
I need to cd /another_file and execute command that will start some game server.
I tried something like
$ssh->write("cd /another_file");
$ssh->write("my command here");
But no success, it's showing commands in same line.
Any ideas how to do that?
You have several options.
Chain the commands using $ssh->write():
$ssh->write("cd /another_file && ls -la\n");
...or...
$ssh->write("cd /another_file; ls -la\n");
Chain the commands using $ssh->exec(). Works much the same way as above except that you don't need to append \n to your command and you don't need to bother with the $ssh->read().
Do multiple $ssh->write() calls, which is what your current attempt is attempting to do. But it's doing it wrong:
$ssh->write("cd /another_file");
$ssh->write("my command here");
In your first code snippet you're appending a \n but you're not doing so on these lines. You need to because, when you're in an interactive shell, the way the shell knows that you're done typing the command out is because you hit the enter button. That's how Linux knows you're done typing and are ready for your command to run.
You also need to read the prompt before running the next command. eg. $ssh->read('[prompt]') or whatever is appropriate for your system. I suppose you could just omit passing a parameter to $ssh->read() all together, as you do in your first code snippet, but then it'll take 10s or so for $ssh->read() to return any output when it could have alternatively been returning output instantly.

Open batch file php [duplicate]

This question already has answers here:
How do you run a .bat file from PHP?
(7 answers)
php How do I start an external program running - Having trouble with system and exec
(3 answers)
Closed 3 years ago.
Before everyone starts butting in with "security risks" "cant be done" stop there and read the ENTIRE post
I have a web server set up from a home laptop which is serving as a games web server im trying to create a GUI so its easier for us to maintain the server and im trying to use batch files to do the actions on the computer
So to put this into perspective I have my index file index.php
<form method="post">
<input type="submit" name="startServer" value="Start Server">
</form>
<?
if(isset($_POST['startServer'])){
exec('batch/startServer.bat');
}
?>
And my startServer.bat will run on the laptop running the server and will do all the actions nesscary to start our game server so there is another directory "Instance" containing an excutable "Server.exe" which the batch file will run
The issue im having is running the web server and testing this it doesnt work if I open the batch file directly it works but it seems the php code doesnt work
For clarification I am using apache and my browser is chrome
And just a quick question for anyone willing to answer the route im going is correct right? Using php would allow everything to run on the machine hosting the server so the end user will only see the GUI and the server would run the batch files and everything on the web server and not the local machine if that makes sense?
EDIT: To be more clear about what's going on the function exec runs but it just hangs like the application is loading I need a solution that will actually open the application are my host computer for example if I wanted to open up notepad I press a button on the Web server and notepad will open on the computer
EDIT 2: I would like to note that I dont exactly need to use the exec function and I have tried all the answers to date 7/19/2017:3:45pm none are working if I do something on the sorts echo exec('start text.bat'); I will get a This is a test to show your batch is working and simply just have echo ..... in the batch file the main issue I am having is the server is not physically showing the opened file like displaying the GUI lets just take notepad for example
I can open notepad and get some return value as long as my batch file closes notepad once its finished running however the GUI for notepad is never displayed and thats very important
I read in a few articles about using apache as a service which im pretty sure I am but I do know that xaammp has suffiecient priveleges and I have checked the box that says "Allow apache to interact with desktop" however no GUI is popping up thats the main point I guess im trying to get across is I need to display the GUI not just open the file as a background service.
If it makes answering easier I am open to switching programming languages if theres one that can do what I want easier
Your theory is correct, it will run on the server however you may have issues running applications directly from php (with this method afaik it does not detach from the PHP, and the webapp "hangs" while the application is running).
Make sure: return values are printed / logged. Just an
<?php
if(isset($_POST['startServer'])){
echo exec('batch/startServer.bat');
}
?>
Could point you to the right direction. The exec function may have been disabled in your distribution.
Using
<?php
instead of
<?
is highly advised, by default short_tags are not enabled in most distributions (wamp, xamp, etc).
Set debug mode and print everything to get information about the problem:
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
if(isset($_POST['startServer'])){
echo exec('batch/startServer.bat');
}
?>
If you don't have any response, try a simple batch file with a "hello world" to test if it works.
Be aware, the rights and limitations are comes from the php environment, the batch file inherits the same rights running the PHP code / Apache (in case of mod_php)
In php manual about exec function, there is a note :
Note: If a program is started with this function, in order for it to
continue running in the background, the output of the program must be
redirected to a file or another output stream. Failing to do so will
cause PHP to hang until the execution of the program ends.
I think "hangs like the application is loading" is your application waiting for the bat file terminated / closed to get the output result
Let's try another approach, i found it here, the concept is to create a scheduler that execute the program you want and call it using command.
hope this help :
shell_exec('SCHTASKS /F /Create /TN _notepad /TR "notepad.exe" /SC DAILY /RU INTERACTIVE');
shell_exec('SCHTASKS /RUN /TN "_notepad"');
shell_exec('SCHTASKS /DELETE /TN "_notepad" /F');
If this doesn't work
Check whether you have declared safe_mode = Off inside php.ini
From here:
How do you run a .bat file from PHP?
Have you tried:
system("cmd /c C:[path to file]"); ?
You might need to run it via cmd, eg:
system("cmd /c C:[path to file]");
Or Try following options
1.
<?php
exec('c:\WINDOWS\system32\cmd.exe /c START C:\Program Files\VideoLAN\VLC\vlc.bat');
?>
2.
When you use the exec() function, it is as though you have a cmd terminal open and are typing commands straight to it.
Use single quotes like this $str = exec('start /B Path\to\batch.bat');
The /B means the bat will be executed in the background so the rest of the php will continue after running that line, as opposed to $str = exec('start /B /C command', $result); where command is executed and then result is stored for later use.
<?php
pclose(popen("start /B test.bat", "r")); die();
?>
i think this is a containment issue.
if you run the app under the process of php run by iiswebuser when php terminates it will close all spawned child processes in windows. there is a very quick way a command to break an application out of the child process containment using the start command.
if(isset($_POST['startServer'])){
exec('start batch/startServer.bat');
}
Diagram of containment as i explained it (simplisticly)
IIS (IIS runs as an IISUser)
php (application)
cmd.exe (batch)
using start bring it to the root of that tree
IIS (IIS runs as an IISUser)
php (application)
cmd.exe (batch)
Baim Wrong was correct in the first part of the response: you have to redirect output of the script or your PHP code will hang. Also, you have to move process in the background.
This is easy to do on *nix:
system("/usr/local/bin/shell.sh >> /tmp/log.log 2>&1 &");
I know that you can redirect the output on Windows but not sure how to move the process in the background. You should check DOS manual or try with power shell.
you can use either system or exec php function
$path = __DIR__ . '/batch/startServer.bat';
exec('cmd /c start ' . $path);
or
$path = __DIR__ . '/batch/startServer.bat';
$lastLine = system('cmd /c start ' . $path);
You are having some issue about running application directly from exec. I was having the same issue of running file using exec. It was solved by passing another parameter 2>&1.
exec('some_command 2>&1', $output);
print_r($output); // to see the response to your command
Check the values printed by output see exec function
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
$output = array();
if(isset($_POST['startServer'])){
exec('batch/startServer.bat 2>&1', $output);
print_r($output);
} else {
echo "Not posted";
}
?>

Not getting output from python script when run through PHP

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.

exec() not working when trying to execute PHP script

I am have a PHP script called process_item.php that can be run from terminal. I want to create a web script that can run the same file using exec(). My web script(process_item_online.php) looks like below:
ini_set("display_errors",true);
error_reporting(E_ALL);
$item = $_GET['item'];
echo "Received request for item $item<br>";
$cmd = "/usr/bin/php /var/www/html/process_item.php $item";
exec($cmd);
echo "Processed using command - $cmd";
The script process_item.php has 777 permissions. When I run the above script in browser, I get both these lines printed correctly:
Received request for item 10023444AJK
Executed command - /usr/bin/php /var/www/html/process_item.php 10023444AJK
However nothing else happens. As in, the database is not updated, the logs are not written etc. I do not get any error on the browser either. I am sure this is a permission issue since it works fine from the terminal. Can anyone give me any pointers on how I can make this work from the browser?

PHP script cannot stop the program which is run from shell script in linux

I wrote a shell script in linux to check if one of my program (say programA) is running, if it stopped, it will restart the program.
ok, I also have a php script which hav start & stop button to start and stop the same program from the server side. If the program is already run by the shell script, clicking on start button will NOT run multiple of the same program.
THE PROBLEM IS: if PHP script works fine by itself. But the PHP script cannot close the program if it is run by the shellscript. Is this a permission issue or something that I havent been aware of? (I already did chmod 777 programA btw...)
UPDATE:
in my PHP script, it calls exec("kill -9 PID_of_programA") to kill the program.
I tried to change it to $r = shell_exec("kill -9 PID_of_programA") and echo $r gives me nothing...
You are probably running your program with a user that has no privileges to close other programs... Have you tried to run as super user?

Categories