Run a .bat file from a Python CGI file with Apache Webserver
<p>This might be really easy. But its just not working for me. </p>

<p>I have a .bat file I would like to run, which performs stuff on the Server, and should send an email with an Attachement.</p>

<p>The .bat file works fine, it sends the email with the log and everything.  </p>

<p>Now I would like to run that file from a Webserver. So that I can click on an HTML form Button, and it executes. </p>

<p>I have installed Apache, Python 2.7 for it. </p>

<p>I have configured Apache to allow cgi files, and It works when I put a file as index.py with following code.</p>

<p>But when I press the Submit button it goes through, but the .bat files is not being executed. Help! :)</p>

<p>Is there another way I can run a .bat file to do stuff on my server from a Webserver maybe? thank you in beforehand. </p>

<p>I tried the action in the form to direct to a .py and .cgi file... don't get it to work</p>

<p>Below the code I a have been using.  </p>

<pre><code>#!/Python27/python
#!/usr/bin/env python
import cgi
import cgitb; cgitb.enable()  
print "Content-type: text/html"
print
print "&lt;html&gt;&lt;head&gt;"
print "&lt;form action='../cgi-bin/send_email.py'&gt;"
print "&lt;input type='submit' value='Submit'&gt;"
print "&lt;/form&gt;"
</code></pre>

<p>send_email.py looks like this. </p>

<pre><code>#!/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()
</code></pre>

<p>You can invoke the batch file with <code>cmd.exe</code>:</p>

<pre><code>...
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)
...
</code></pre>

python windows apache batch-file