Run a .bat file from a Python CGI file with Apache Webserver - python

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)
...

Related

Python stderr redirect to file

I'm trying to redirect stderr to a file, and I've read the numerous posts here, but it's not working for me on a Pi or on my Win laptop.
Hoping someone will see what's wrong.
Using IDLE -
On Pi, the file is written but is empty, and stderr (traceback - /0) wasn't written to the IDLE shell....
On Win, the file is written but is empty, and stderr (traceback - /0 ) still appears in the IDLE shell.
import sys
import time
sys.stderrr = open('errout.txt', 'w')
print("stderr redirected now.")
i = 1/0
Change stderrr to stderr and you should be okay

How to switch users for Python CGI Programming?

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

run python script as cgi apache server

I am trying to make a python script run as cgi, using an Apache server. My script looks something like this:
#!/usr/bin/python
import cgi
if __name__ == "__main__":
print("Content-type: text/html")
print("<HTML>")
print("<HEAD>")
I have done the necessary configurations in httpd.conf(in my opinion):
<Directory "/opt/lampp/htdocs/xampp/python">
Options +ExecCGI
AddHandler cgi-script .cgi .py
Order allow,deny
Allow from all
</Directory>
I have set the execution permission for the script with chmod
However, when I try to access the script via localhost i get an Error 500:End of script output before headers:script.py
What could be the problem? The script is created in an Unix like environment so I think the problem of clrf vs lf doesn't stand. Thanks a lot.
I think you are missing a print statement after
print("Content-type: text/html")
The output of a CGI script should consist of two sections, separated by a blank line. The first section contains a number of headers, telling the client what kind of data is
following.
The second section is usually HTML, which allows the client software to display nicely formatted text with header, in-line images, etc.
It may look like
#!/usr/bin/env python
print "Content-Type: text/html"
print
print """
<TITLE>CGI script ! Python</TITLE>
<H1>This is my first CGI script</H1>
Hello, world!
"""
For more details visit python-cgi
For python3
#!/usr/bin/env python3
print("Content-Type: text/html")
print()
print ("""
<TITLE>CGI script ! Python</TITLE>
<H1>This is my first CGI script</H1>
Hello, world!
"""
)

running a python script on server

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.

How can I tell whether screen is running?

I am trying to run a Python program to see if the screen program is running. If it is, then the program should not run the rest of the code. This is what I have and it's not working:
#!/usr/bin/python
import os
var1 = os.system ('screen -r > /root/screenlog/screen.log')
fd = open("/root/screenlog/screen.log")
content = fd.readline()
while content:
if content == "There is no screen to be resumed.":
os.system ('/etc/init.d/tunnel.sh')
print "The tunnel is now active."
else:
print "The tunnel is running."
fd.close()
I know there are probably several things here that don't need to be and quite a few that I'm missing. I will be running this program in cron.
from subprocess import Popen, PIPE
def screen_is_running():
out = Popen("screen -list",shell=True,stdout=PIPE).communicate()[0]
return not out.startswith("This room is empty")
Maybe the error message that you redirect on the first os.system call is written on the standard error instead of the standard output. You should try replacing this line with:
var1 = os.system ('screen -r 2> /root/screenlog/screen.log')
Note the 2> to redirect standard error to your file.

Categories