Python CGI os.system causes invalid header

I am running Apache / 2.4.10 (Raspbian) and I am using python for CGI. But when I try to use os.system in simple code, I get this error with the wrong header:

[Wed Aug 31 17:10:05.715740 2016] [cgid:error] [pid 3103:tid 1929376816] [client 192.168.0.106:59277] malformed header from script'play.cgi': Bad header: code.cgi

Here is the code from play.cgi:

#!/usr/bin/python
# -*- coding: UTF-8 -*-
import cgi
import os

print('Content-type: text/html')
print('')

os.system('ls')

The strange thing is that if I delete the os.system line, it mysteriously starts working again. Instead, I tried using popen, the same problem. I tried to disguise it in some code, change the file name, various encodings and even time.sleep, none of them worked.

The strangest thing is that it works fine in more complex code.

+2
source share
1 answer

To find out why the problem occurred, try running the script

python webls.py > output

output . , Content-type: text/html , , , .

- , outout os.system Python- ( : print(...) , , os.system() os.system transacton, ( , outout )). , .

#!/usr/bin/python

import cgi
import os
import sys

print 'Content-type: text/html'
print ''

sys.stdout.flush()

os.system('ls')

, , - , - os.system. , . ( ):

- /. ls Python:

os.system('ls > /tmp/lsoutput')
print open('/tmp/lsoutput', 'r').read()

- . python ( python getoutput() )

import subprocess
process = subprocess.Popen(['ls', '-a'], stdout=subprocess.PIPE)
out, err = process.communicate()
print(out)

- , . , Python

import os

for filename in os.listdir('.'):
    print filename
+2

Source: https://habr.com/ru/post/1653362/


All Articles