Costales
Costales

Reputation: 2873

How to avoid Shell Injection with a path variable and wait for command exist?

I need to read the exit of a command (then I have to wait for it in sync way):

import subprocess
subprocess.call('ls ~', shell=True)

My problem is a path like this:

~/testing/;xterm;/blabla

How could I sanitize that string from user (allowing special characters from his language)?

import subprocess
subprocess.call('ls ~/testing/;xterm;/blabla', shell=True) # This will launch xterm

I found escapeshellcmd in PHP, but I didn't find anything in Python.

PS: It's not a duplicate of this:

Thanks in advance!

=======

Upvotes: 3

Views: 2083

Answers (1)

falsetru
falsetru

Reputation: 369364

Pass a list instead of a string. And remove shell=True to make the command are not run by shell. (You need to expand ~ yourself using os.path.expanduser)

import os
import subprocess

subprocess.call(['ls', os.path.expanduser('~') + '/testing/;xterm;/blabla'])

Side note: If you want to get list of filenames, you'd better to use os.listdir instead:

filelist = os.listdir(os.path.expanduser('~') + '/testing/;xterm;/blabla')

Upvotes: 4

Related Questions