How do I execute linux grep using python? My current attempt is the following
output = subprocess.run(
"/bin/grep " + query,
cwd=path_to_files,
stdout = subprocess.PIPE,
stderr = subprocess.PIPE,
shell=True
)
Which works. Issue however is that query can include untrusted commands (eg. if they append a semicolon in the query, they can possibly run a second command in addition to the initial grep). How could I securely accept user inputs to the grep command?
shell=True. You need to restrict the query as much as possible. And that will depend on your use-caseshell=Trueis what makes this query dangerous. If I remove shell=True, subprocess would not execute by throwing aFileNotFoundErrorerror. I would like to give my users access to use grep on a single folder, recursively.shell=True. Usechrootjail. Maybe symlink thegrepbinary to the local directory to get around theFileNotFoundErrorquery?-r "pokedex" */*.htmlinto the input. Which translate to thequeryvariable.