从 Web 表单以 root 身份调用 CGI Python 脚本

从 Web 表单以 root 身份调用 CGI Python 脚本

我很难让 Web 表单运行需要以 root 权限执行命令的 CGI 脚本。表单如下:

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

Python 脚本打印消息.py是可执行的(-rwxr-xr-x 1 root root)并且仅将字符串打印到浏览器的版本工作正常,因此 apache 的 CGI 设置似乎没问题。

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

当 root 运行它时,它有效。我编辑/etc/sudoers如下:

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

不确定这是否意味着 www-data 可以以 root 身份运行该脚本,或者它是否无需调用就可以运行该脚本sudo?现在,当我调用该页面时,我得到:

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/

是不是我的 sudoers 行不正确?非常感谢您的帮助。

答案1

如果您不想每次安装时都请求 root 访问权限,请执行以下操作:https://github.com/quick2wire/quick2wire-gpio-admin

答案2

#!/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()
  1. 跨域?
  2. 不能暂停CGI(0.1 秒的延迟将会损坏您的数据)

像这样 :

import cgi # Maybe need form value etc.
form = cgi.FieldStorage()

myVar = "Failed : "
def myHandler(myVar = myVar):
    try :
        #Do stuf here !
        myVar = myContent

    except Exception,e :
        myVar += str(e)

myHandler()#we don't need any arguments !

print "Content-Type: text/html;charset=utf-8;" # What is your ContentType ?
print "Access-Control-Allow-Origin:*"
print
print myVar

这是基本流程图(请勿在未确保安全的情况下以此方式使用)

相关内容