python - 在 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')
可能吗 ?
感谢您的帮助 !
解决方案
您可以使用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
的命令(在某种程度上)是无辜的,但很容易利用获得访问权限的命令。
推荐阅读
- vba - 在抓取维基百科 URL 时避免 Google IP 阻塞
- javascript - 我们如何检查在 sap ui5 中单击了哪些图块?根据点击的图块调用不同的方法是什么?
- ajax - 在 WordPress 中使用 ajax 动态填充选择
- php - 只有 64 张图片正在发送到服务器
- syntax - 如何从此语法中消除歧义(antlr4)
- javascript - Highcharts 多列的平均值
- javascript - 我的js游戏不断分配和释放内存
- django - Dockerized Django REST Framework / Postgresql - 不允许的主机
- android - 如何将 @IntRange() 支持注释应用于 Kotlin 属性设置器
- react-native - 反应本机地图mapPadding不起作用