Search code examples
pythonterminalcommandcgilighttpd

Lighttpd cgi python fail to run system processes


I'm trying to run terminal commands from a web python script. I tried many things but none seens to work... Such as: add 'www-data' to sudoers, use full path to bin, run command with sudo word, use 3 different system calls (os.spawnl and subprocess) and none of that works. Read only commands like "ps aux" that only output information works, but a simple echo to file don't. It seens like need permitions to do so. What more can i try?

Example from output: Unexpected error: (, CalledProcessError(2, '/bin/echo hello > /var/www/html/cgi-bin/test2.htm'), )

On that example the /var/www/html/cgi-bin/ folder is owned by "www-data", same user as server config.

<!-- language: python -->
#!/usr/bin/python3
# coding=utf-8
import os
import sys
import subprocess
import cgi
import subprocess

SCRIPT_PATH = "/var/www/html/scripts/aqi3.py"
DATA_FILE = "/var/www/html/assets/aqi.json"
KILL_PROCESS = "ps aux | grep " + SCRIPT_PATH + " | grep -v \"grep\" | awk '{print $2}' | xargs kill -9"
START_PROCESS = "/usr/bin/python3 " + SCRIPT_PATH + " start > /dev/null 2>&1 &"
STOP_PROCESS = "/usr/bin/python3 " + SCRIPT_PATH + " stop > /dev/null 2>&1 &"


# Don't edit
def killProcess():
    os.spawnl(os.P_NOWAIT, KILL_PROCESS)
    try:
        os.spawnl(os.P_NOWAIT, "/bin/echo hello > /var/www/html/cgi-bin/test2.htm")
        proc = subprocess.Popen(['sudo', 'echo', 'hello > /var/www/html/cgi-bin/test3.htm'])
        print(subprocess.check_output("/bin/echo hello > /var/www/html/cgi-bin/test2.htm", shell=True, timeout = 10))
    except:
        print("Unexpected error:", sys.exc_info())

    print(KILL_PROCESS)


def stopSensor():
    killProcess()
    os.spawnl(os.P_NOWAIT, STOP_PROCESS)


def restartProcess():
    killProcess()
    print(START_PROCESS)
    print(os.spawnl(os.P_NOWAIT, START_PROCESS))


def main():
    arguments = cgi.FieldStorage()
    for key in arguments.keys():
        value = arguments[key].value
        if key == 'action':
            if value == 'stop':
                stopSensor()
                print("ok")
                return
            elif value == 'start' or value == 'restart':
                restartProcess()
                print("ok")
                return
            elif value == 'resetdata':
                try:
                    with open(DATA_FILE, 'w') as outfile:
                        outfile.write('[]')
                except:
                    print("Unexpected error:", sys.exc_info())

                print("ok")
                return

    print("?")


main()

Solution

  • I was able to solve my problem with: http://alexanderhoughton.co.uk/blog/lighttpd-changing-default-user-raspberry-pi/