Skip to content

Instantly share code, notes, and snippets.

@gdugas
Last active December 9, 2015 23:38
Show Gist options
  • Save gdugas/4345360 to your computer and use it in GitHub Desktop.
Save gdugas/4345360 to your computer and use it in GitHub Desktop.
return a absolute path jailed in a rootpath
import os
"""
return a absolute path jailed in a rootpath
example:
securejoin('/home/john/', 'path1/../../path2')
> /home/john/path2
"""
def securejoin(rootpath, path):
path = os.path.join(path).split('/')
safe = []
for i in range(len(path)):
if path[i] == '' or path[i] == '.':
continue
elif path[i] == '..':
if len(safe) > 0:
safe.pop()
else:
continue
else:
safe.append(path[i])
return os.path.join(rootpath, '/'.join(safe))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment