CGI Python os.system

时间:2012-05-10 21:22:41

标签: python apache cgi

我只是想知道是否可以从Apache上的CGI脚本运行系统调用。这是代码的一部分:

print "<input type = 'submit' value = 'Launch Job!'>"
print "</form>"
print "</body>"
print "</html>"
system('command')

我正在尝试在托管网页的同一台计算机上运行此命令。问题是当执行此函数时,命令无法成功运行。我尝试将sudo添加到开头,尝试os.system('command')都无济于事。

那么,这可能吗?

2 个答案:

答案 0 :(得分:0)

命令将以用户nobody的形式运行,并且几乎没有权限。

答案 1 :(得分:0)

尝试子流程

#!/usr/bin/python
import subprocess
a = subprocess.check_output(["date"]) # this is your command
#print os_date
print "Content-type:text/html\r\n\r\n"
print '<html>'
print '<head>'
print '<title>Hello Word!</title>'
print '</head>'
print '<body>'
print '<h2>Hello Word! Today is: %s</h2>' % a
print '</body>'
print '</html>'

如果服务器显示500错误,请尝试 cgi

#!/usr/bin/python

try:
    import cgitb; cgitb.enable()
except:
    pass
import sys, cgi, os
sys.stderr = sys.stdout
from time import strftime
import traceback
from StringIO import StringIO
from traceback import print_exc


if __name__ == '__main__':
    print "Content-type: text/html"         
    print                                   
    form = cgi.FieldStorage()
    thecmd = "python yourscript.py" # this is your command
    if thecmd:
        print '<HR><BR><BR>'
        print '<B>Command : ', thecmd, '<BR><BR>'
        print 'Result : <BR><BR>'
        try:
            child_stdin, child_stdout = os.popen2(thecmd)
            child_stdin.close()
            result = child_stdout.read()
            child_stdout.close()
            print result.replace('\n', '<BR>')

        except Exception, e:                
            print errormess
            f = StringIO()
            print_exc(file=f)
            a = f.getvalue().splitlines()
            for line in a:
                print line