Python – Calling CGI python script as root from a web form

apache-2.2cgipython

I'm having difficulty getting a web form to run a CGI script that needs to perform a command with root permission. The form is:

<form class="mainform" action="./py/print_msg.py" method="POST">
    <textarea name="post" cols=70 rows=20></textarea><br>
    <input type="submit" value="Print" class="button">
    <input type="reset" value="Clear" class="button">
</form>

The python script print_msg.py is executable (-rwxr-xr-x 1 root root) and a version that just prints strings to the browser work ok, so apache's CGI settings seems ok.

#!/usr/bin/env python

from Adafruit_Thermal import *

print "Content-type: text/html\n\n"

printer = Adafruit_Thermal("/dev/ttyAMA0", 19200, timeout=5)
printer.wake()
time.sleep(1)
print "test"
printer.sleep()

This works when root runs it. I've edited /etc/sudoers as follows:

www-data ALL=(ALL) NOPASSWD: /usr/bin/sudo -u root /home/pi/www/html/py/print_msg.py

Not sure if this means www-data can run that script as root or if it will do so without needing to invoke sudo? Now when I call the page I get:

Traceback (most recent call last):
  File "/var/www/html/py/print_msg.py", line 7, in <module>
    printer = Adafruit_Thermal("/dev/ttyAMA0", 19200, timeout=5)
  File "/home/pi/www/html/py/Adafruit_Thermal.py", line 73, in __init__
    Serial.__init__(self, *args, **kwargs)
  File "/usr/lib/python2.7/dist-packages/serial/serialutil.py", line 261, in __init__
    self.open()
  File "/usr/lib/python2.7/dist-packages/serial/serialposix.py", line 278, in open
    raise SerialException("could not open port %s: %s" % (self._port, msg))
serial.serialutil.SerialException: could not open port /dev/ttyAMA0: [Errno 13] Permission denied: '/dev/ttyAMA0'
[Wed Jun 01 13:50:04.383712 2016] [cgid:error] [pid 30345:tid 2993681456] (104)Connection reset by peer: [client 192.168.1.158:51239] AH02550: Failed to flush CGI output to client, referer: http://192.168.1.174/

Do I not have the right sudoers line perhaps? Grateful for assistance.

Best Answer

If you don't want to request root access each time you need to install this: https://github.com/quick2wire/quick2wire-gpio-admin

Related Topic