Thanks for your time.
I took a new VPS, just to put online a software I'm developing. The VPS is on CentOs 7. I've installed HTTPD and PHP, Python was already installed. The index page is online.
I've found a sample at cyberwarzone and I've created an index.php page like this:
<html>
<body>
<form action="#" method="post">
Name: <input type="text" name="NAME"><br>
<input type="submit" value="NAME">
</form>
</body>
</html>
<?php
error_reporting(E_ALL);
$param1 = $_POST["NAME"];
$command = escapeshellcmd("/var/www/html/cyberwarzone.py $param1 ");
$resultAsString = shell_exec($command);
echo $resultAsString;
?>
And a cyberwarzone.py file like this:
#!/usr/bin/python
import sys
workvalue = sys.argv[1]
workvalue = workvalue + '\t' + "Hello World, send from Cyberwarzone.py"
print(workvalue)
Now, when I enter any data, nothing happens. Python is in /usr/bin/python and html files are in /var/www/html/. Can anybody help me to troubleshoot it?
Thanks.
I've found the problem. I was saving the .py file with windows EOL. Changing them, in NP++, resolved the problem. Thanks for your time
Related
I am trying to create a webapp and am fairly new to it. I have a python script(file.py) that transforms data selected by a user. It handles all the inputs and outputs.
I am using flask(main.py) for the server part of it and html. I want to place a button in my html code so it will start the execution of the file.py. Can anyone assist me with an example setup for the connections between the 3?
I've looked at other examples but I'm unable to recreate it as they're doing different things. Also, file.py is fairly large so I want to avoid putting it into a function.
Edit: not looking for a flask tutorial. I've tried 3things:
A shell pops up for half a second but the disappears. Then I'm redirected to a page which just has the text in my return statement
in my html file
<form action="/pic" method="POST">
<input type="submit" value="GET THE SCRIPT">
</form>
in my main.py flask file
#app.route('/pic', methods=['GET', 'POST'])
def pic():
os.system("python file.py") #file.py is the script I'm trying to start
return "done"
Doesn't do anything at all.
in html file:
<input type="button" id='script' name="scriptbutton" value=" Run Script " onclick="goPython()">
<script src="http://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
<script>
function goPython(){
$.ajax({
url: "/scripts/file.py",
context: document.body
}).done(function() {
alert('finished python script');;
});
}
</script>
I get a GET "/scripts/file.py HTTP/1.1" 404 message. I have my scripts folder in the same directory as my templates folder. Also tried placing the scripts folder inside the templates folder.
in html
<form action="/run" method = "POST">
<input type="button" id='script' name="submit" value="Run Scripttttttt">
</form>
in flask main.py
#app.route('/run',methods=['GET', 'POST'])
def index():
def inner():
proc = subprocess.Popen(
['python file.py'],
shell=True,
stdout=subprocess.PIPE
)
for line in iter(proc.stdout.readline,''):
time.sleep(1)
yield line.rstrip() + '<br/>\n'
return Flask.Response(inner(), mimetype='text/html')
Using an HTML Anchor tag (i.e ) is the easiest way. Here is an example:
This is a link
But since you've chosen button, JavaScript will come in handy. Here's an example(inline):
<button onclick="window.location.href='your_flask_route';">
This is a link
</button>
and then in your flask main.py file you should have this:
#app.route('/your_flask_route')
def your_flask_route():
'''some lines of code'''
You can set up a Flask endpoint that your button can send a request to. Then let the endpoint's function call your python script.
Have a look at this discussion about Flask - Calling python function on button OnClick event and this discussion about How can I make one python file run another? to get you started.
I am creating a project on a raspberry pi using a motion detector to send a text message. Having some issues executing a python script from PHP (Apache2).
Trying to execute this python script:
#!/usr/bin/env python
from gpiozero import MotionSensor
import time
import os
#Motion sensor in GPIO23
ms = MotionSensor(23)
def send_notification():
#Debug Motion Statement
print("There was a movement!")
#Notification script is stored in notification variable
notification = os.popen ('bash /home/pi/project/notification.sh')
#Send Notification
print(notification.read())
#Delay between notifications
time.sleep(15)
#Execute send_notification function on motion
ms.when_motion = send_notification
The notification.sh script for reference. It uses postfix to send a text message.
echo "Motion was detected in your Smart Mailbox!" | mail myphonenumber#vtext.com
From this PHP code:
<!DOCTYPE html>
<html>
<head>
<title>Smart Mailbox</title>
<link rel="stylesheet" type="text/css" href="styles.css">
</head>
<div class="form-style-5">
<body style="text-align:center;">
<h1>Smart Mailbox Application</h1>
<p>Enter Your Phone Number:</p>
<form method="post">
<input type="tel" name="phonenumber" placeholder="10 Digit Phone Number" pattern="[0-9]{10}" required>
<br>
<p>Select Your Phone Carrier:</p>
<select name="carrierdropdown" required>
<option value=""></option>
<option value="Verizon">Verizon</option>
<option value="ATT">ATT</option>
<option value="Sprint">Sprint</option>
<option value="TMobile">T-Mobile</option>
</select>
<br><br>
<input type="submit" name="submit" value="Start SmartMailbox">
</form>
</body>
</div>
</html>
<?php
if(isset($_POST['submit'])) {
//Appends phone carrier address to email address
if($_POST['carrierdropdown']=="Verizon"){
//echo "DEBUG:Verizon";
$carrier = "#vtext.com";
} elseif ($_POST['carrierdropdown']=="ATT"){
//echo "DEBUG:ATT";
$carrier = "#txt.att.net";
} elseif ($_POST['carrierdropdown']=="Sprint"){
//echo "DEBUG:Sprint";
$carrier = "#messaging.sprintpcs.com";
} elseif ($_POST['carrierdropdown']=="TMobile"){
//echo "DEBUG:T-Mobile";
} else{
echo "Break";
}
//Gets users phone number from HTML form
$phonenumber = $_POST['phonenumber'];
//Opens notification script for editing
$file = fopen('/var/www/html/notification.sh','w');
//Writes mail command to file appending phonenumber
fwrite($file,'echo "Motion was detected in your Smart Mailbox!" | mail ' . $phonenumber . $carrier);
//Closes file
fclose($file);
//Runs python scripts
exec('node /home/pi/project/blynkconnect.js');
exec('python -i /home/pi/project/MotionNotification.py &');
}
?>
This following command works on the command line alone. I have to use the -i flag so that the session will stay open to detect motion.
python -i /home/pi/project/MotionNotification.py &
So I suppose my issue is running this from PHP (I am using apache2 web server to host). All files have read,write,execute permissions. The node command I am running from PHP works flawlessly FYI. I have tried to give the apache web user root access and still no luck.
Any ideas I can give a try? Thanks!
I found this CGI Module, its letting me use HTML tags inside a python script.
ive seen some topics in here that shows how to use it, but when im using it it doesnt works.
import cgi
print ("""
<html>
<body>
Hello
</body>
</html>
""")
and this is the output when im running the script:
<html>
<body>
Hello
</body>
</html>
how can i use this properly?
thanks.
If you have your CGI script already hooked up to a web server, you will need to emit the HTTP headers too, e.g.
print("Content-Type: text/html") # HTML is following
print() # blank line, end of headers
print ("""
<html>
<body>
Hello
</body>
</html>
""")
Note that the cgi module is not being used in any way to achieve this; just simple calls to print(). The module is useful when you want to process form data submitted by a client through a HTML form.
I am building a simple web app (posted part of it yesterday) but I am struggling with a portion:
1) Request a text file to upload
2) Save the uploaded file to a directory
I am using python and cgi for this. cgi is working as confirmed with a simple test.cgi file.
Here is my current code for request_input.cgi:
#!/usr/bin/python
import cgi
print "Content-type: text/html\r\n\r\n"
print '<html>'
print '<body>'
print '<form enctype="multipart/form-data" action="save_input.cgi" method="post">'
print '<p>File: <input type="file" name="filename" /></p>'
print '<p>input type="submit" value="Upload" /></p>'
print '</form>'
print '</body>'
print '</html>'
Now when I tail the apache error log I get the following errors:
"(2)No such file or directory: exec of '/var/www/ipcheck/request_input.cgi' failed, referer: [http://192.168.3.77/ipcheck/?C=M;O=A]"
"Premature end of script headers: request_input.cgi, referer [http://192.168.3.77/ipcheck/?C=M;O=A]"
Any help would be awesome! Thanks a lot
dos2unix resolved issue. Built in windows, moved to linux. Thanks for the help.
I simply copied all of the code in the file, opened a new python window, pasted the code into it and saved it under the same name (to overwrite the old file). Hope this helps!
I am writing a python script to run on a apache web server. My first goal is to list the network interfaces that are available and, after, for each one, build a form to input some parameters of interest. My problem is that when I run the following script from the command line I get the expected result (a formatted html web page with form(s)) while if I assess it from the web, i.e. putting the script in my web server and remotely access it through http://myipaddr/cgi-bin/myscript.py, I get only the submission button and not the form(s).
#!/usr/bin/python
# import required modules
import re
import cgi
from subprocess import *
var=Popen("ifconfig", stdout=PIPE, shell=True).stdout.read()
result = re.findall("wlan[1-9]", var)
def DisplayForm():
HTMLFormL1= '\n\nInterface:<BR> <INPUT TYPE=TEXT NAME="interface%d" size=60><BR>\n'
HTMLFormL2= 'Number of packets to send:<BR> <INPUT TYPE=TEXT NAME="npackets%d" size=60><BR>\n'
HTMLFormL3= 'Transmission channel:<BR> <INPUT TYPE=TEXT NAME="channel%d" size=60><BR>\n'
HTMLFormL4= 'Sleep time in usec:<BR> <INPUT TYPE=TEXT NAME="sleeptime%d" size=60><BR><BR><BR>\n'
HTMLForm = HTMLFormL1 + HTMLFormL2 + HTMLFormL3 + HTMLFormL4
HTMLStart = '<FORM METHOD="POST" ACTION="caos.py">\n<INPUT TYPE=HIDDEN NAME="key" VALUE="process">\n'
for num in range(len(result)):
HTMLForm_idx = HTMLForm % (num, num, num, num)
HTMLStart = "%s%s" % (HTMLStart, HTMLForm_idx)
HTMLBody = HTMLStart + '\n<BR><P><INPUT TYPE="SUBMIT" VALUE="Configure">\n</FORM>\n'
print "Content-Type: text/html\n\n"
HTMLHeader ='<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN">\n<html>\n<head>\n<META NAME="keywords" CONTENT="blah blah -- your ad here">\n<title>CAOS</title>\n</head>\n<body>'
HTMLFooter ='</body>\n</html>'
print HTMLHeader
print HTMLBody
print HTMLFooter
#--- Begin of "main"
form = cgi.FieldStorage()
try:
key = form["key"].value
except:
key = None
if key != "process":
DisplayForm()
I have looked for a similar problem, but I could not find anything similar on the web. Most likely I'm doing something stupid, but I cannot figure it out myself. I would very happy if someone could point me the right direction.
Cheers,
bman
Probably different versions of python are being run.
Check if your ssh user and web server user (www) is running same python from same path.
Try commenting out Popen and replace result with mock values. If Popen is causing the problem (as I suspect), you probably will want to obtain the values in a different manner than through an stdout pipe.