i want to run a python script from php code using exec or shell_exec. this is php code :
<?php
exec('/usr/bin/python /var/www/html/test.py');
?>
also this is the python script i want to execute it from browser, name test.py :
#!/usr/bin/env python
import os
f= open("/var/www/html/result","w")
f.write("ok")
script runs from command line correctly, but when i execut it from browser , it dose not work. I searched a lot of things and i did following items to solve the problem :
I add 'www-data ALL=(ALL) NOPASSWD: ALL' and 'apache ALL=(ALL) NOPASSWD: ALL' in /etc/sudoers file.
I give 777 permission to /var/www/html directory
I run 'chown -R www-data:www-data /var/www/html'
Remove all functions in front of 'disable_functions' in /etc/php/7.0/fpm/php.ini and /etc/php/7.0/cli/php.ini files
home.php and test.py are in a same directory in /var/www/html
I login with www-data in commandline and executed test.py and it worked correctly
But still the script dose not work when i visit http://server_ip_address/home.php . I'm new in php and apache. can anybody help me to solve the problem. great thanks
Can you try
<?php
exec('/usr/bin/python3 /var/www/html/test.py');
?>
and
#!/usr/bin/env python3
import os
f= open("/var/www/html/result","w")
f.write("ok")
Related
I am new to web design, and I'm trying to setup an Apache web interface to some python code.
I am running a test python script that just opens a new file in /var/www/html/ called output.txt and attempts to write to it. When the web page is loaded, I use shell_exec('/usr/bin/python3 /var/www/html/ptest.py'); to run my python script. The python script does run and outputs some print messages, but trying to open output.txt fails with:
Traceback (most recent call last): File "/var/www/html/ptest.py", line 8, in f=open("/var/www/html/output.txt", "w") PermissionError: [Errno 13] Permission denied: '/var/www/html/output.txt'. It will also fail if the file already exists and I open to read.
I have confirmed that the script is being run by apache with getpass.getuser(), and I have tried as many different permission combinations as I can think of for /var/www/html/, including 777. I have set apache as the group for every directory from /var/ to html/. I have tried creating the file ahead of time with 777 permissions. I have checked that /var/ to html/ has group execution permission.
I have tried creating and using another folder completely owned by apache.
I have looked through the apache directives to see if there is a directive I need to have, but I haven't found one yet.
I've included the code for my python script and my php page below.
EDIT: I've tried running ptest.py as apache using su -s /bin/bash apache.
ptest.py successfully runs this way, so the problem doesn't seem to be a permission associated with the apache user/group.
ptest.py
#!/usr/bin/python3
import sys
import getpass
import os
sys.stderr = sys.stdout
print(getpass.getuser())
print(os.getgid())
f = open("/var/www/html/output.txt", "w")
f.write("banana")
f.close()
print("I wrote banana, which is a berry")
banana.php
<html>
<head></head>
<body>
<h2>Welcome to the Program Test</h2>
<?php
echo "Created Command", "<br>";
$output = shell_exec('/usr/bin/python3 /var/www/html/ptest.py');
echo "Executed Command", "<br>";
echo $output, "<br>";
echo "End of output", "<br>";
$output = shell_exec('ls /var/www/html/');
echo $output;
?>
</body>
</html>
Credit to domino_pl leaving a comment.
It looks like typical selinux problem. Try selinux setenforce 0 – domino_pl
i´ve a few problems with my python3 scripts.
an php script start an python3 script:
$comando = 'python3 /var/www/html/tmp/' . $usersession . '-newtenent-vcenter1.py';
shell_exec("/usr/bin/nohup ".$comando." >/dev/null 2>&1 &");
the python3 script write a few strings to an new created text file.
After all thinks are done, the script sould be start the next python3 script:
os.system('python3 /var/www/html/tmp/' + usersession + '-newtenent-cucm1.py')
BUT, python3 start the script "cucm1.py" and close it imeadlety! The script shoud be open an ssh session with paramiko.
The OS is an Ubuntu 18.x. I´ve added the www-data user to the script directory (so all scripts can be executed by the user www-data):
www-data ALL=(ALL) NOPASSWD: /usr/bin/python3 /var/www/html/
BUT, when we execute the first python3 script from the linux shell (as root) it work´s fine (the second script working fine).
any idea? THANK YOU!
I have followed a few posts on here trying to run either a python or shell script on my ec2 instance after every boot not just the first boot.
I have tried the:
[scripts-user, always] to /etc/cloud/cloud.cfg file
Added script to ./scripts/per-boot folder
and
adding script to /etc/rc.local
Yes the permissions were changed to 755 for /etc/rc.local
I am attempting to pipe the output of the file into a file located in the /home/ubuntu/ directory and the file does not contain anything after boot.
If I run the scripts (.sh or .py) manually they work.
Any suggestions or request for additional info to help?
So the current solution appears to be a method I wrote off in my initial question post as I may have not performed the setup exactly as outline in the link below...
This link -->
How do I make cloud-init startup scripts run every time my EC2 instance boots?
The link shows how to modify the /etc/cloud/cloud.cfg file to update scripts-user to [scripts-user, always]
Also that link says to add your *.sh file to /var/lib/cloud/scripts/per-boot directory.
Once you reboot your system your script should have executed and you can verify this in: sudo cat /var/log/cloud-init.log
if your script still fails to execute try to erase the instance state of your server with the following command: sudo rm -rf /var/lib/cloud/instance/*
--NOTE:--
It appears print commands from a python script do not pipe (>>) as expected but echo commands pipe easily
Fails to pipe
sudo python test.py >> log.txt
Pipes successfully
echo "HI" >> log.txt
Is this something along the lines that you want?
It copies the script to the instance, connects to the instance, and runs the script right away.
ec2 scp ~/path_to_script.py : instance_name -y && ec2 ssh instance_name -yc "python script_name.py" 1>/dev/null
I read that the use of rc.local is getting deprecated. One thing to try is a line in /etc/crontab like this:
#reboot full-path-of-script
If there's a specific user you want to run the script as, you can list it after #reboot.
I've been trying to launch a python script at the boot of the Rpi, but everything I've tried until now did not work.
The script is some version of this : https://www.raspberrypi.org/learning/temperature-log/worksheet/ :
#!/usr/bin/python
import os, sys
from subprocess import check_output
from re import findall
from time import sleep, strftime, time
def get_temp():
temp = check_output(["vcgencmd","measure_temp"]).decode("UTF-8")
temp = float(findall("\d+\.\d+",temp)[0])
return(temp)
while True:
log=open("cpu_temp.txt","a")
temp = get_temp()
log.write("{0} {1}".format(strftime("%Y-%m-%d %H:%M:%S"),str(temp))+" degreeC\r\n")
sleep(60)
log.close()
It works fine on its own. I tried editing crontab, with and without the absolute path to Python, as well as editing /etc/rc.local
I know it doesn't work, because it should create a text file and edit it each minute, and it's not created at boot. I have other commands in crontab and rc.local that are working.
Need some help please !
If your script is located at /home/pi/tempcheck.py the you should edit crontab with
sudo crontab -e
and append the line
#reboot python /home/pi/tempcheck.py &
then save and exit.
Further details can be found at http://www.raspberrypi-spy.co.uk/2013/07/running-a-python-script-at-boot-using-cron/
You can check it is running with
ps aux | grep tempcheck.py
Note that if you edit root's crontab, the python process will be run as root. So you should use absolute filenames in the python script:
log=open("/home/pi/cpu_temp.txt","a")
sudo crontab -e
#reboot /usr/bin/python /path/to/file/script.py
/path/to/file/script.py would probably be something like /home/username/script.py
If it still doesn't work you can try giving it execute permission with this:
chmod a+x script.py
You can call your script in the ~/.bashrc file. It will be called at boot or terminal opening.
Just write :
python /path/to/your/script.py
At the end of the .bashrc file.
I have a short Python script that needs to run at startup - Ubuntu 13.10. I have tried everything I can think of but can't get it to run. The script:
#!/usr/bin/python
import time
with open("/home/username/Desktop/startup.txt", 'a') as f:
f.write(str(time.time()) + " It worked!")
(The actual script is a bit different, as I'm just using this for testing purposes, but you get the idea.)
I've tried all of the following, with no luck:
Put the command python startuptest.py in crontab, as #reboot
python /home/username/Documents/startuptest.py, both as the regular user and as sudo
Put the command python /home/username/Documents/startuptest.py in /etc/rc.local
Opened Ubuntu's Startup Applications and put the command there
Done all of the preceding, putting the command into a shell script
and calling that shell script instead
Nothing works. I get the feeling I'm missing something simple. Any ideas? (The script runs fine if I just run the command from a terminal.)
Instructions
Copy the python file to /bin:
sudo cp -i /path/to/your_script.py /bin
Add A New Cron Job:
sudo crontab -e
Scroll to the bottom and add the following line (after all the #'s):
#reboot python /bin/your_script.py &
The “&” at the end of the line means the command is run in the background and it won’t stop the system booting up.
Test it:
sudo reboot
Practical example:
Add this file to your Desktop: test_code.py (run it to check that it works for you)
from os.path import expanduser
import datetime
file = open(expanduser("~") + '/Desktop/HERE.txt', 'w')
file.write("It worked!\n" + str(datetime.datetime.now()))
file.close()
Run the following commands:
sudo cp -i ~/Desktop/test_code.py /bin
sudo crontab -e
Add the following line and save it:
#reboot python /bin/test_code.py &
Now reboot your computer and you should find a new file on your Desktop: HERE.txt
Put this in /etc/init (Use /etc/systemd in Ubuntu 15.x)
mystartupscript.conf
start on runlevel [2345]
stop on runlevel [!2345]
exec /path/to/script.py
By placing this conf file there you hook into ubuntu's upstart service that runs services on startup.
manual starting/stopping is done with
sudo service mystartupscript start
and
sudo service mystartupscript stop
If you are on Ubuntu you don't need to write any other code except your Python file's code , Here are the Steps :-
Open Dash (The First Icon In Sidebar).
Then type Startup Applications and open that app.
Here Click the Add Button on the right.
There fill in the details and in the command area browse for your Python File and click Ok.
Test it by Restarting System . Done . Enjoy !!
Create file ~/.config/autostart/MyScript.desktop
with
[Desktop Entry]
Encoding=UTF-8
Name=MyScript
Comment=MyScript
Icon=gnome-info
Exec=python /home/your_path/script.py
Terminal=false
Type=Application
Categories=
X-GNOME-Autostart-enabled=true
X-GNOME-Autostart-Delay=0
It helps me!
In similar situations, I've done well by putting something like the following into /etc/rc.local:
cd /path/to/my/script
./my_script.py &
cd -
echo `date +%Y-%b-%d_%H:%M:%S` > /tmp/ran_rc_local # check that rc.local ran
This has worked on multiple versions of Fedora and on Ubuntu 14.04 LTS, for both python and perl scripts.
nano /etc/rc.local
and edit in
python ~/path-to-script.py
worked for me