首页 > 解决方案 > 在 django 服务器下使用 cmd 行

问题描述

为了更容易理解,我将使用简单的命令行作为' ls'

我如何在 django 服务器中使用像 ' pwd' 或 ' ' 这样的命令行?ls

例如,我的 django 服务器正在运行 ' python manage.py runserver'

在我的代码中,我想运行一个像 ' pwd' 这样的 cmd 命令并得到这个命令的输出:

@login_required
def history(request):
    list_file = print('ls') #i would like to do 'ls' command
    return render(request, 'history.html')

可能吗 ?

感谢您的帮助 !

标签: pythondjango

解决方案


您可以使用subprocess模块 [python-doc],例如subprocess.run(…)[python-doc]

from subprocess import run, PIPE

@login_required
def history(request):
    result = run('ls', stdout=PIPE)
    response = result.stdout
    return render(request, 'history.html', {'response': response})

但是,您应该小心不要将 shell 访问权限授予用户。如果您允许用户运行任意命令,他们可以接管服务器,例如通过将 Django 代码替换为其他一些代码等。虽然类似ls的命令(在某种程度上)是无辜的,但很容易利用获得访问权限的命令。


推荐阅读