【问题标题】:CGI Python os.systemCGI Python 操作系统
【发布时间】:2023-12-12 13:56:02
【问题描述】:

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

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

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

那么,这可能吗?

【问题讨论】:

  • 解释你想要做什么可能会有所帮助。也许您不需要使用外部实用程序?

标签: python apache cgi


【解决方案1】:

命令将以nobody 用户身份运行,并且权限很少。

【讨论】:

  • 谢谢路易斯,有什么办法可以改变吗?
  • 您可以设置可执行文件的setuid位,这意味着它将以文件所有者的权限运行。 警告如果所有者是root,这可能会带来严重的安全风险。例如,您可以创建一个由 apache 用户拥有的包装脚本。
  • 您可以让服务器以普通用户的身份运行,接受请求以通过 dbus 或套接字执行某些操作。然后 cgi 脚本可以请求启动作业。
【解决方案2】:

尝试子流程

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

【讨论】:

    最近更新 更多