Reputation: 407
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?
Upvotes: 2
Views: 191
Reputation: 1280
Insead of use shell=True
, you can send a list to subprocess.run
.
import shlex
output = subprocess.run(
["/bin/grep "] + shlex.split(query),
cwd=path_to_files,
stdout = subprocess.PIPE,
stderr = subprocess.PIPE
)
This code prevent using ;
for shell injection.
Another problem is that the user can access all files in the system.
You can use chroot
for prevent a user to go above that the given file or you can modify your code for to be able to check which file the user will open.
Upvotes: 1