Skip to content

Instantly share code, notes, and snippets.

@eoldavix
Last active November 15, 2017 12:39
Show Gist options
  • Select an option

  • Save eoldavix/a584c4b854441138aba8469d17f2cccb to your computer and use it in GitHub Desktop.

Select an option

Save eoldavix/a584c4b854441138aba8469d17f2cccb to your computer and use it in GitHub Desktop.
Unix 'ls' permissions to octal
import re
ISAPERM = r'(^[ld\-](?:[r\-][w\-][x\-sS]){2}[r\-][w\-][x\-tT](?:\.)?$)'
def to_octal(perms):
if re.compile(ISAPERM).match(perms):
userperms = perms[1:4]
groupperms = perms[4:7]
otherperms = perms[7:10]
numericaluserperms = int(b"".join(str(x) for x in map(lambda x:
1 if x != '-' else 0, userperms)),
2)
numericalgroupperms = int(b"".join(str(x) for x in map(lambda x:
1 if x != '-' else 0, groupperms)),
2)
numericalotherperms = int(b"".join(str(x) for x in map(lambda x:
1 if x != '-' else 0, otherperms)),
2)
# Special permissions
numericalspecialperms = 0
if 's' in userperms.lower():
numericalspecialperms += 4
if 'S' in userperms:
numericaluserperms -= 1
if 's' in groupperms.lower():
numericalspecialperms += 2
if 'S' in groupperms:
numericalgroupperms -= 1
if 't' in otherperms.lower():
numericalspecialperms += 1
if 'T' in otherperms:
numericalotherperms -= 1
return "{}{}{}{}".format(numericalspecialperms, numericaluserperms,
numericalgroupperms, numericalotherperms)
else:
return None
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment