2

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 !

asked Nov 24, 2020 at 19:39
4
  • 1
    You can use 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. Commented Nov 24, 2020 at 19:41
  • Ok thank you, that work. Commented Nov 24, 2020 at 19:57
  • Can you answer the question with your current answer please? I'll mark it as answered :) Commented Nov 25, 2020 at 16:43
  • answered the question :). Commented Nov 25, 2020 at 18:06

1 Answer 1

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.

answered Nov 25, 2020 at 18:06
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.