File deletion using rm command

webminal.org picture webminal.org · Feb 16, 2010 · Viewed 26.6k times · Source

I want to make sure that I delete required files. I have code something like

dir="/some/path/"
file = "somefile.txt"
cmd_rm= "rm -rf "+dir + file
os.system(cmd_rm)

The dir and file values are fetched from a database. How can I make sure I never end up running rm -rf /?

What things should I check before doing rm -rf?

Answer

sth picture sth · Feb 16, 2010

Don't use the -r switch if you just want to remove a single file. Also, there could be spaces in the file name.

Better use the functions in Python's os module instead:

dirname = "/some/path/"
filename = "somefile.txt"
pathname = os.path.abspath(os.path.join(dirname, filename))
if pathname.startswith(dirname):
   os.remove(pathname)

Normalizing the path with abspath and comparing it against the target directory avoids file names like "../../../etc/passwd" or similar.