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!
Related
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
My form is this:
<form name="mail-me" action="/mail-me.py" method="POST" enctype="multipart/form-data">
<input id='file' type='file' name='file' />
I am doing this within python (I'm using the native google python dev_appserver webapp2.RequestHandler bindings):
fileH = self.request.POST["file"]
print(fileH.name)
print(fileH.type)
and i get:
file
application/octet-stream
The file I'm uploading is: wodim.conf so I should get wodim.conf instead of file. What am I doing wrong - how do i fix this, because I get:
Error: Server Error
The server encountered an error and could not complete your request.
Please try again in 30 seconds.
request.FILES['filename'].name
From the request documentation.
You can iterate over the files:
for filename, file in request.FILES.iteritems():
name = request.FILES[filename].name
Figured it out, did a: print(dir(fileH)) - that gave me a list of supported attributes and filename is what I should be using, not 'file'. So, print(fileH.filename) works. I'm getting the server error because google-app-server only allows a fixed list of extensions (no .exe is allowed for uploading). If you do: fname = fileH.file 'file' is returned and this will cause problems since it has no extension (hence the error message).
I really searched about 50 related pages but never seen a problem similar to my problem. When I press the submit button, it calls the script but the script returns an empty page and I see no file was uploaded. There is no typing error in my codes, I checked it several times and I really need this code running for my project. What might be the problem? I am running apache under ubuntu and my codes are:
html code:
<html><body>
<form enctype="multipart/form-data" action="save_file.py" method="post">
<p>File: <input type="file" name="file"></p>
<p><input type="submit" value="Upload"></p>
</form>
</body></html>
python code:
#!/usr/bin/env python
import cgi, os
import cgitb; cgitb.enable()
try: #windows needs stdio set for binary mode
import msvcrt
msvcrt.setmode (0, os.O_BINARY)
msvcrt.setmode (1, os.O_BINARY)
except ImportError:
pass
form = cgi.FieldStorage()
#nested FieldStorage instance holds the file
fileitem = form['file']
#if file is uploaded
if fileitem.filename:
#strip leading path from filename to avoid directory based attacks
fn = os.path.basename(fileitem.filename)
open('/files' + fn, 'wb').write(fileitem.file.read())
message = 'The file "' + fn + '" was uploaded successfully'
else:
message = 'No file was uploaded'
print """\
Content-Type: text/html\n
<html><body>
<p>%s</p>
</body></html>
""" % (message,)
I just tested your script, with a few small corrections to the paths to make it work for me locally. With the paths set correctly, and permissions set properly, this code does work fine.
Here are the things to make sure of:
In your html file's form properties, make sure you are pointing to the python script that lives in a cgi-bin: action="/cgi-bin/save_file.py". For me, I have a cgi-bin at the root of my web server, and I placed the python script there. It will not work if you are running the script from a standard document location on the web server
Make sure your save_file.py has executable permissions: chmod 755 save_file.py
In your save_file.py, ensure that you are building a valid path to open the file for saving. I made mine absolute just for testing purposes, but something like this: open(os.path.join('/path/to/upload/files', fn)
With those points set correctly, you should not have any problems.
I have written a little survey using Python and CGI. I am trying to show a picture using the normal <img> tag, But even-though the picture is in the same directory as my cgi script, my script cannot show it. I also changed the header to this:
print "Content-type: text/html; image/jpeg"
print
print """<html>
<head>
<title>You are going to be redirected</title>
</head>
<body bgcolor = #14b585>
<br>
<p align=center><font>Helloooo</font></p>
<img src="cat.jpeg" alt="cat" width="304" height="228"/>
<form action="./sample.py" method="post">
<p align=center><input type="submit" value="YES!" /></p>
</form>
</body>
</html>
"""
Why?(it is a very small jpg file)
print "Content-type: text/html; image/jpeg"
Don't change the header to that. You can't have multiple content types for a single document (multipart documents excluded, but browsers don't support them and that isn't the right format).
You are delivering an HTML document with an reference to an image in it. The image will be a separate request and response.
print "Content-type: text/html"
Or, better:
print "Content-type: text/html; charset=utf-8"
(Assuming you are using utf-8, which you should be).
print """<html>
Your Doctype is missing. This will trigger quirks mode, which is undesirable. You also have a great deal of legacy presentational markup that should be replaced by CSS.
<img src="cat.jpeg" alt="cat" width="304" height="228"/>
The context suggests that the image is decorative, so the alternative text should probably be "" (see Alt texts in IMGS), but there is nothing wrong with the actual reference to the image.
But even-though the picture is in the same directory as my cgi script
Since the HTML seems to be OK. You need to check that the image is.
Can you reach the image by typing the URL in directly?
What do the web server logs say when you try?
It is possible that your server is configured to try to treat everything in the directory as an executable, no matter what the file extension, so it might be trying to run the image as if it were a CGI program (which will obviously fail). If so, then you could either move the image or change the configuration of the server.
And I've just noticed this comment:
I did this in my browser: localhost/cgi-bin/cat.jpg and it got an error, I checked the logs, it Exec format error: exec of '/home/hossein/public_html/cgi-bin/cat.jpg' failed
That is what is happening. Moving the image is the simplest solution.
your apache was configured to use the cgi-bin directory as an CGI scripts folder, so any request that trying to get a file from this folder apache try to execute it as an CGI script. to make your image visible move it to the www/html folder.
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.