I have an HTML form which is handled by a Python script using CGI programming. From my Python script, I want to switch users from apache2 to monkey. The reason is because I'm using os.system to run another script from within my Python script.
The Python script works fine but I keep getting Permission errors when executing this command: os.system('python other_script.py'). What I realize is that when I am running the HTML form, I am apache2 instead of monkey. I'd like to know how to switch users (as monkey not root) while executing the Python script.
Here is what my Python script looks like:
#!/usr/bin/python -W
# Import modules for CGI handling
import cgi, cgitb
import pwd
import grp
import sys
import os
# Create instance of FieldStorage
form = cgi.FieldStorage()
print "Content-type:text/html\r\n\r\n"
print '<html>'
print '<head>'
print '<title>Hello Word - First CGI Program</title>'
print '</head>'
print '<body>'
print '</body>'
print '</html>'
os.system('python other_script.py') # getting permission errors here
Related
This might be really easy. But its just not working for me.
I have a .bat file I would like to run, which performs stuff on the Server, and should send an email with an Attachement.
The .bat file works fine, it sends the email with the log and everything.
Now I would like to run that file from a Webserver. So that I can click on an HTML form Button, and it executes.
I have installed Apache, Python 2.7 for it.
I have configured Apache to allow cgi files, and It works when I put a file as index.py with following code.
But when I press the Submit button it goes through, but the .bat files is not being executed. Help! :)
Is there another way I can run a .bat file to do stuff on my server from a Webserver maybe? thank you in beforehand.
I tried the action in the form to direct to a .py and .cgi file... don't get it to work
Below the code I a have been using.
#!/Python27/python
#!/usr/bin/env python
import cgi
import cgitb; cgitb.enable()
print "Content-type: text/html"
print
print "<html><head>"
print "<form action='../cgi-bin/send_email.py'>"
print "<input type='submit' value='Submit'>"
print "</form>"
send_email.py looks like this.
#!/Python27/python
#!/usr/bin/env python
import cgi
import cgitb; cgitb.enable()
from subprocess import Popen
p = Popen("batch.bat", cwd=r"C:\Path\to\batchfolder")
stdout, stderr = p.communicate()
You can invoke the batch file with cmd.exe:
...
cmd = r'c:\Windows\System32\cmd.exe'
batDir = r'C:\Path\to\batchfolder'
batName = r'batch.bat'
p = Popen(r"{0} /C {1}\{2}".format(cmd,batDir,batName), cwd=batDir)
...
i am a beginner in python. I've installed python34, and xampp. I've changed the http.config file and added the .py extension in handler block. then i put my python script into xamp/bin-cgi and set the first line of the python script as, "#!C:/Python34/python.exe". But when i opens the file through localhost/cgi-bin/test.py it doesn't showing anything only a blank screen, Below the content of the file.
#!C:/Python34/python.exe
print "Content-type: text/html"
print
print "<html>"
print "<head>"
print "<title>welcome cgi</title>"
print "</head>"
print "<body>"
print "<h1>first python page</h1>"
print "<p>heihei</p>"
print "</body>"
print "</html>"
You should rewrite the first line like this:
#!"C:\Python34\python.exe"
You are using Python 2.7 with your print statements. That is the first error. YOu are calling the Python 3.4 interpreters.
Also, you need to change your first line to
#!/Python34/python
# -*- coding: UTF-8 -*-
# enable debugging
Then, change your print statements to have parentheses
print("Content-type: text/html")
print()
print("""<html>
<head>
<title>welcome cgi</title>
</head>
<body>
<h1>first python page</h1>
<p>heihei</p>
</body>
</html>""")
ATTENTION:
If you notice, I changed up your code a bit and got rid of a bunch of print statements. Instead, I used what's called a multiline string (instead of writing "blah" I would do """blah"""). For example if I did
print("asdasdasd
asdasdasdasdasd")
This wouldn't work
But, if I changed it to
print("""asdasdasdasdasd
asdasdasdasdasd""")
This would be a perfectly acceptable command. Every new line would be registered as a "\n" so really, the string we are printing out is "asdasdasdasdasd\nasdasdasdasdasd" where \n marks a new line
The code is running and inserting but I get errors in command prompt saying 'tab' is not recognised as an internal or external command,operable program or batch file.
What is the mistake i have done and How can i fix it ?
Here is the python code :
updatedb.py
import sqlite3 as db
import urllib
import re
import sys
url=sys.argv[1]
htmltext=urllib.urlopen(url).read()
regex='<title>(.+?)</title>'
pattern=re.compile(regex)
title= re.findall(pattern,htmltext)
print title[0]
id="1"
conn=db.connect('insertlinks.db')
cursor=conn.cursor()
with conn:
cursor.execute('insert into records (id,keyword) values(?,?)',(id,title[0]))
#print "inserted"
#conn.close()
The above code is called as follows:
import urlparse
import os
import urllib
from bs4 import BeautifulSoup
url="http://www.google.com"
urls=[url]
visited=[url]
try:
while len(urls)>0:
htmltext=urllib.urlopen(urls[0]).read()
soup=BeautifulSoup(htmltext)
urls.pop(0)
for tag in soup.findAll('a',href=True):
tag['href']=urlparse.urljoin(url,tag['href'])
if tag['href'] not in urls and tag['href'] not in visited:
os.system("python scraper/insertlinks.py %s" % (tag['href']))
os.system("python scraper/updatedb.py %s" % (tag['href']))
urls.append(tag['href'])
visited.append(tag['href'])
except:
print 'error in 1'
EDIT:
The problem is in tag['href']. Its value is http://maps.google.co.in/maps?hl=en&tab=il. The tab in the url is creating a problem. How do i solve it?
Use the subprocess.call() method instead of os.system()
The & in the url is what is causing the problem.
On Windows:
Command1 & Command2
Means run Command1 then run Command2
The error you are getting is a Windows error, not a Python error. Somehow one or both of your os.system calls are passing "tab" as a command to the Windows command line.
I suspect this is because many of the urls on the google.com page have ?tab=Wx or &tab=wT or other similar arguments tacked on to the url. The ? shouldn't hurt anything, but the & may be interpreted as the start of another command. (If that is the case, I would expect you to receive errors about a lot more than just 'tab' though.)
Is there a python equivalent to this in perl?
use CGI;
my $IN = new CGI;
print $IN->header();
# $IN->header(-type=>'image/gif');
I see that this will print a header along with the ENV information:
import cgi
cgi.test()
Obviously I don't need the ENV information when not debugging. Otherwise do I need to type the print "Content-type: text/html" or print "Content-type: image/gif" everytime or is there a module already written that is similar?
i have a python script on the server
#!/usr/bin/env python
import cgi
import cgitb; #cgitb.enable()
import sys, os
from subprocess import call
import time
import subprocess
form = cgi.FieldStorage()
component = form.getvalue('component')
command = form.getvalue('command')
success = True
print """Content-Type: text/html\n"""
if component=="Engine" and command=="Start":
try:
process = subprocess.Popen(['/usr/sbin/telepath','engine','start'], shell=False, stdout=subprocess.PIPE)
print "{ans:12}"
except Exception, e:
success = False
print "{ans:0}"
When I run this script and add the component and command parameters to be "Engine" and "Start" respectively - it starts the process and prints to the shell
"""Content-Type: text/html\n"""
{ans:12}
but most importantly - it starts the process!
however, when I run the script by POSTing to it, it returns {ans:12} but does not run the process which was the whole intention in the first place. Any logical explanation?
I suspect it's one of two things, firstly your process is probably running but your python code doesn't handle the output so do:
process = subprocess.Popen(['/usr/sbin/telepath','engine','start'], shell=False, stdout=subprocess.PIPE)
print process.stdout.read()
This is the most likely and explains why you see the output from the command line and not the browser, or secondly because the script is run through the browsers as the user apache and not with your userid check the permission for /usr/sbin/telepath.