To make it easier to understand, i will use simple command line as 'ls'
How can i use a command line like 'pwd' or 'ls' into a django server ?
For example, my django server is running 'python manage.py runserver'
And into my code i would like to run a cmd command like 'pwd' and get the output of this command :
@login_required
def history(request):
list_file = print('ls') #i would like to do 'ls' command
return render(request, 'history.html')
Is it possible ?
Thank for your help !
1 Answer 1
You can make use of subprocess module [python-doc], for example 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})
You should however be careful not to give shell access to users. If you allow users to run arbitrary commands, they can take over the server, for example by replacing the Django code with some other code, etc. Although commands like ls are (to some extent) innocent, it is easy to exploit a certain feature of a command to gain access.
subprocess.run(docs.python.org/3/library/subprocess.html#subprocess.run) but beware that this is a security vulnerability. If you give shell access (to some extent), people can try to take over the server.